push_back
ing to a vector of non-const elements works as expected:
std::vector<int> foo;
int bar = 0;
foo.push_back(bar);
But why is the following not possible?
std::vector<const int> foo;
const int bar = 0;
foo.push_back(bar);
More precisely, why is creating the foo
object possible but not calling push_back
on it?
You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state.
If the vector itself is declared const (as in const std::vector<T*>), then you can't modify the vector, but you can modify the objects. If the pointers are declared const (as in std::vector<const T*>), then you can modify the vector, but not the objects.
vector::push_back() push_back() function is used to push elements into a vector from the back. The new value is inserted into the vector at the end, after the current last element and the container size is increased by 1.
push_back effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.
According to this answer (with commentary from one of the C++11 designers), std::vector<const T>
is not permitted by the Standard.
The answer suggests that it might be possible to supply a custom allocator which permits a vector with that allocator to hold const objects.
You're probably better off not attempting to do this.
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