#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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With