3
#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace std;

struct TestMe
{
    TestMe() : i(10), j(20) {}
    int i;
    int j;
};

int main()
{
   // Case I:
   //vector<const int> vec;
   /*
/usr/local/gcc-4.8.1/include/c++/4.8.1/ext/new_allocator.h:93:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const int; __gnu_cxx::new_allocator<_Tp>::const_pointer = const int*; __gnu_cxx::new_allocator<_Tp>::const_reference = const int&]' cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT   
   */

   // Case II:        
   //vector<const TestMe> vecTest;

   // Case III:
   //boost::shared_ptr<vector<const TestMe>> shVecTestMe;
   //shVecTestMe = boost::make_shared<vector<const TestMe> >( );    
   return 0;
}

I have tried the above code in two compilers:

1> http://www.compileonline.com/compile_cpp11_online.php

2> MS VS2010

The first compiler cannot accept all cases (i.e. CaseI, Case II, Case III). However, MS VS2010 accepts all of them.

Question 1> Are the cases meaningful? In other words, is it necessary to use

vector<const int>
vector<const TestMe>
boost::shared_ptr<vector<const TestMe>>

to prevent the contained value is modified later.

Question 2> Why two compilers have different responses on those cases. Which one is correct based on c++ standard?

Thank you

q0987
  • 34,938
  • 69
  • 242
  • 387
  • 1
    To give you an answer, no you aren't allowed to use const in an STL container per the standards. Doing so results in undefined behavior. Similar thread: http://stackoverflow.com/questions/4940419/vc-allows-to-use-const-types-for-stl-containers-why – jakebower Feb 26 '14 at 18:20

2 Answers2

1

A const object by definition means that it is not going to change after creation. Thus you can't create a vector of const int unless you reference const objects that already exist on compilation.

The question is... why the need for this? Do people change your vector all the time?

There are other mechanisms to enforce this, like a private vector in a class.

Claudiordgz
  • 3,023
  • 1
  • 21
  • 48
0

As mentioned in the comments and the possibly duplicate questions and their answers, this results in undefined behavior, that's why compilers / library implementations are behaving differently. For instance, GCC's library implementation is trying to overload a method over a const and a non-const reference, which fails if the reference type is already const.

But it is not meaningful either. You can just say

const vector<int> vec;

and I cannot imagine if there's anything more you could achieve with your vector <const int> if it were valid.

iavr
  • 7,547
  • 1
  • 18
  • 53