`vector<const T>`的用法 [英] usage of `vector<const T>`

查看:39
本文介绍了`vector<const T>`的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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> 微软 VS2010

2> MS VS2010

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

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

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

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.

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

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

谢谢

推荐答案

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

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.

这篇关于`vector&lt;const T&gt;`的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆