Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector<const int> is not allowed. Why is pair<const int, int> allowed? [duplicate]

Tags:

c++

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 pairs inside a map object. Am I missing something?

Detailed and intuitive explanations of this phenomenon would be greatly appreciated.

like image 274
Dennis Ritchie Avatar asked Dec 07 '12 17:12

Dennis Ritchie


People also ask

What does a const vector mean in C++?

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.

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.

Can you push const vector back?

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.


2 Answers

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).

like image 54
prazuber Avatar answered Nov 15 '22 06:11

prazuber


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.

like image 22
Puppy Avatar answered Nov 15 '22 08:11

Puppy