Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const references in std::vector elements

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?

like image 534
mip Avatar asked May 10 '12 09:05

mip


People also ask

Can std::vector hold references?

std::reference_wrapper It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

Can you have a vector of references in C++?

It's a flaw in the C++ language. You can't take the address of a reference, since attempting to do so would result in the address of the object being referred to, and thus you can never get a pointer to a reference.

Can references be const?

The grammar doesn't allow you to declare a “const reference” because a reference is inherently const . Once you bind a reference to refer to an object, you cannot bind it to refer to a different object.

Can vectors be const?

If we desire that the elements of a vector should not be modified, we can declare that vector as a const vector. However, we must initialize this vector when it is declared, as it is not possible to modify it subsequently. Thus, a const vector can be declared and initialized as shown below.


2 Answers

You may want to check

std::reference_wrapper

available with C++11

like image 187
stefan bachert Avatar answered Sep 25 '22 03:09

stefan bachert


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.

like image 39
hmjd Avatar answered Sep 23 '22 03:09

hmjd