3

I declared a vector of constant integers, but its element can be changed.

 vector<const int> v;
 int a = 5;
 v.push_back(a);
 v[0] = 8;

 cout << "Vector elements:" << endl;
 for( size_t i=0; i<v.size(); i++){
    cout << v[i] << ' ';
 }
 cout << endl;

The output is

Vector elements:
8

I think the element should not be able to change because it is a constant. Can anybody let me know what I am missing here?

I am using Visual Studio 2012 on Windows 7.

Thanks in advance!

leo
  • 357
  • 2
  • 15
  • 1
    Can not reproduce in `GCC 6.2.1`, a bug in `VS`? – Galik Oct 04 '16 at 04:02
  • 1
    Try printing this: `std::cout << std::is_same::value_type>::value << std::endl;`. If it prints `1` (or `true`), then you know `std::vector` removes the `const` from the template argument. – Nawaz Oct 04 '16 at 04:05
  • 2
    http://stackoverflow.com/questions/22049747/usage-of-vectorconst-t?noredirect=1&lq=1 – Mat Oct 04 '16 at 04:09
  • If it kept the const, you'd get a compiler error on `v[0] = 8;` because it would be setting a value to a const reference – kmdreko Oct 04 '16 at 04:11
  • 1
    Cannot reproduce in VS2015: `error C3892: 'v': you cannot assign to a variable that is const` – David Scarlett Oct 04 '16 at 04:21

0 Answers0