Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I push_back to a vector of const elements? [duplicate]

push_backing 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?

like image 718
emlai Avatar asked Mar 01 '15 06:03

emlai


People also ask

Can you push back to a const vector?

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.

Can a const vector be modified?

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.

What does vector Push_back do?

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.

Does push back increase the size of a vector?

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.


1 Answers

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.

like image 181
M.M Avatar answered Sep 23 '22 05:09

M.M