11

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?

Emil Laine
  • 41,598
  • 9
  • 101
  • 157

1 Answers1

14

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.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365