12
votes

Is it only my compiler or is it forbidden to use cons references in std::vector elements. Consider following structure:

struct Y
{
  const int & x;

  Y(const int & p_x):
        x(p_x)
  {
  }
};

Now, when I try to push such object onto vector:

std::vector<Y> yv;
int x = 5;
Y y(x);
yv.push_back(y);

I get compiler error: "error: non-static reference member `const int&Y::x', can't use default assignment operator". Shouldn't copy ctor be enough?

6

6 Answers

21
votes

The vector elements must be assignable. From section 23.2.4 Class template vector of the C++ standard:

...the stored object shall meet the requirements of Assignable.

12
votes

You may want to check

std::reference_wrapper

available with C++11

5
votes

No, because you can't assign to a const reference and the STL containers make use of assignment for moving items around.

You're better using a shared_ptr (boost:: or std:: depending on your environment) or a raw pointer.

1
votes

An assignment operator is necessary because vector default constructs elements in extra slots ahead of time.

Later, instead of reallocating, it uses the assignment operator to assign those default instances to whatever you push into the vector.

0
votes

It is generally forbidden to use references in any container. You can justify this by the fact, that a vector for example allocates the data in forehand and references can just be assigned once (during initialization).

0
votes

I finally used

 std::vector< const Type* >

Not the best looking, but it does the same job.