Possible Duplicate:
Why does stack<const string> not compile in g++?
An answer to another question
explained why we (supposedly) can't have containers of const
objects. For example, this is not allowed:
vector<const int> v; //not allowed
But why does a pair
allow the first object to be const
? This is, indeed, what happens with the pair
s inside a map
object. Am I missing something?
Detailed and intuitive explanations of this phenomenon would be greatly appreciated.
A const vector will return a const reference to its elements via the [] operator . In the first case, you cannot change the value of a const int&. In the second case, you cannot change the value of a reference to a constant pointer, but you can change the value the pointer is pointed to.
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.
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.
I think the main reason why is because std::pair
does not reallocate objects, so they don't have to be assignable.
Update:
Actually vector is the only container that requires assignable objects. This is because accordingly to the standard vector must have a contiguous storage location for it's elements. So if there will be no room for more objects to add, vector will have to reallocate it's data to another place (thus using the assignable property of the objects).
std::pair
only needs it's contents to be assignable if you attempt to assign to it. However, std::vector
always requires assignment for reallocation purposes.
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