8

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.

Community
  • 1
  • 1
Dennis Ritchie
  • 1,281
  • 1
  • 10
  • 15

2 Answers2

18

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

prazuber
  • 1,352
  • 10
  • 26
  • 1
    Thanks. By the way, the reason for my `const` obsession is so that I don’t accidentally modify things I did not plan on modifying in the first place. In this case, I don’t wan to modify the container elements, only add to the container. Maybe I should start using `deque` instead of a `vector`? – Dennis Ritchie Dec 07 '12 at 18:41
  • @DennisRitchie: `const vector` may be the answer you're looking for. – prazuber Dec 07 '12 at 18:57
  • I need to be able to add elements to the container, and making the whole vector `const` doesn't allow that, does it? I only want to make sure I can't change elements that are already in the container. – Dennis Ritchie Dec 07 '12 at 19:10
  • 2
    @DennisRitchie: Excuse me, I am deeply sorry for my misunderstanding. If you don't want to modify elements of vector, you can use const iterators. In general case, you might find helpful [this article](http://www.cprogramming.com/tutorial/const_correctness.html). – prazuber Dec 07 '12 at 19:33
7

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • Hm. With the new move semantics, would that still hold true? – Nikos C. Dec 07 '12 at 17:36
  • @NikosC. I suppose the vector just uses move assignment in that case, which is still an assignment. Just a guess though. Someone correct me if I'm wrong. – Dennis Ritchie Dec 07 '12 at 17:42
  • 1
    @NikosC type will have to be Copyable OR Movable. So for example you can have a vector of unique_ptr, which are not Copyable. – nunojpg Jun 05 '17 at 13:08