c++ - `vector<const T>` 的用法

标签 c++ visual-studio-2010

<分区>

#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

2>微软VS2010

第一个编译器无法接受所有情况(即 CaseI、Case II、Case III)。 但是,MS VS2010 接受所有这些。

问题1>这些案例有意义吗?也就是说,有没有必要用

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

防止后面修改包含的值。

问题 2> 为什么两个编译器对这些情况有不同的 react 。根据 C++ 标准,哪一个是正确的?

谢谢

最佳答案

根据定义,const 对象意味着它在创建后不会改变。因此,除非引用编译时已存在的 const 对象,否则不能创建 const int vector 。

问题是……为什么需要这个?人们是否一直在改变您的 vector ?

还有其他机制可以强制执行此操作,例如类中的私有(private) vector 。

关于c++ - `vector<const T>` 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049747/

相关文章:

c++ - 为 UDP 服务器响应重用 sock_fd 与新 sock_fd

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 生成具有它们之间差异的随机坐标

c# - Visual Studio 可以将 U+20000 Unicode 作为字符处理吗?如何?

c++ - Windows 无法加载位图图像

C++代码性能字符串比较

c++ - 我可以使用 Eclipse 作为新的跨平台 GUI 的框架吗?

c++ - 如何通过 HTTPS POST 正确发送二进制数据?

visual-studio-2010 - 将 Entity Framework 模型添加到项目

visual-studio - 是否可以从 Visual Studio 2010 创建 Office 2003 VSTO 加载项?