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?
std::reference_wrapper It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.
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.
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.
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.
You may want to check
std::reference_wrapper
available with C++11
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With