使用` vector<;常数T>` #包括 #包括 #包括 #包括 使用名称空间std; 结构测试 { TestMe():i(10),j(20){} int i; int j; }; int main() { //案例一: //向量向量机; /* /usr/local/gcc-4.8.1/include/c++/4.8.1/ext/new_allocator.h:93:7:错误:“constTp*gnucxx::new分配器::address(gnucxx::new分配器::const引用)const[带Tp=const int;重载的gnu新分配器::const指针=const int*&&新分配器=const引用]”不能被重载 地址(常量引用)常量GLIBCXX\u无例外 */ //案例二: //向量向量机试验; //案例三: //boost::shared_ptr shVecTestMe; //shVecTestMe=boost::make_shared(); 返回0; }

使用` vector<;常数T>` #包括 #包括 #包括 #包括 使用名称空间std; 结构测试 { TestMe():i(10),j(20){} int i; int j; }; int main() { //案例一: //向量向量机; /* /usr/local/gcc-4.8.1/include/c++/4.8.1/ext/new_allocator.h:93:7:错误:“constTp*gnucxx::new分配器::address(gnucxx::new分配器::const引用)const[带Tp=const int;重载的gnu新分配器::const指针=const int*&&新分配器=const引用]”不能被重载 地址(常量引用)常量GLIBCXX\u无例外 */ //案例二: //向量向量机试验; //案例三: //boost::shared_ptr shVecTestMe; //shVecTestMe=boost::make_shared(); 返回0; },c++,visual-studio-2010,C++,Visual Studio 2010,我在两个编译器中尝试了上述代码: 1> 2> MS VS2010 第一个编译器不能接受所有案例(即案例一、案例二、案例三)。 然而,MS VS2010接受所有这些 问题1>案例是否有意义?换句话说,是否有必要使用 #include <iostream> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> using namespace

我在两个编译器中尝试了上述代码:

1>

2> MS VS2010

第一个编译器不能接受所有案例(即案例一、案例二、案例三)。 然而,MS VS2010接受所有这些

问题1>案例是否有意义?换句话说,是否有必要使用

#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;
}
向量
矢量
boost::共享\u ptr
为了防止以后修改包含的值

问题2>为什么两个编译器对这些案例有不同的回答。哪个是正确的基于C++标准?< /P>
谢谢

根据定义,const对象意味着它在创建后不会改变。因此,除非引用编译中已经存在的常量对象,否则无法创建常量int的向量

问题是。。。为什么需要这样做?人们总是改变你的向量吗


还有其他机制来实施这一点,比如类中的私有向量。

如注释和可能重复的问题及其答案中所述,这会导致未定义的行为,这就是编译器/库实现行为不同的原因。例如,GCC的库实现试图在
常量
和非
常量
引用上重载方法,如果引用类型已经是
常量
,则会失败

但这也没有什么意义。你可以说

vector<const int>
vector<const TestMe>
boost::shared_ptr<vector<const TestMe>>
const向量向量向量;

我无法想象如果你的
向量有效的话,你还能做什么。

给你一个答案,不,根据标准,你不能在STL容器中使用const。这样做会导致未定义的行为。类似螺纹:
const vector<int> vec;