#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;
}
我在两个编译器中尝试了上面的代码:
1> http://www.compileonline.com/compile_cpp11_online.php http://www.compileonline.com/compile_cpp11_online.php
2> 微软VS2010
第一个编译器不能接受所有情况(即情况 I、情况 II、情况 III)。
然而,MS VS2010 接受所有这些。
问题1> 这些案例有意义吗?换句话说,是否有必要使用
vector<const int>
vector<const TestMe>
boost::shared_ptr<vector<const TestMe>>
以防止稍后修改包含的值。
问题 2> 为什么两个编译器对这些情况有不同的响应。根据 C++ 标准,哪一个是正确的?
谢谢
根据定义,const 对象意味着它在创建后不会更改。因此,除非引用编译时已存在的 const 对象,否则无法创建 const int 向量。
问题是......为什么需要这个?人们总是改变你的向量吗?
还有其他机制可以强制执行此操作,例如类中的私有向量。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)