【发布时间】:2011-08-16 23:52:39
【问题描述】:
const int * 和 int *const 非常不同。 const std::auto_ptr<int> 与 std::auto_ptr<const int> 类似。但是,const std::vector<int> 与 std::vector<const int> 似乎没有这种区别(实际上我不确定是否允许使用第二个)。这是为什么呢?
有时我有一个函数,我想将引用传递给向量。该函数不应该修改向量本身(例如,没有push_back()),但它想修改每个包含的值(例如,增加它们)。类似地,我可能希望一个函数只更改向量结构而不修改其任何现有内容(尽管这很奇怪)。这种事情用std::auto_ptr(例如)是可能的,但是因为std::vector::front()(例如)被定义为
const T &front() const;
T &front();
不仅仅是
T &front() const;
没有办法表达。
我想做的例子:
//create a (non-modifiable) auto_ptr containing a (modifiable) int
const std::auto_ptr<int> a(new int(3));
//this works and makes sense - changing the value pointed to, not the pointer itself
*a = 4;
//this is an error, as it should be
a.reset();
//create a (non-modifiable) vector containing a (modifiable) int
const std::vector<int> v(1, 3);
//this makes sense to me but doesn't work - trying to change the value in the vector, not the vector itself
v.front() = 4;
//this is an error, as it should be
v.clear();
【问题讨论】:
-
我没有看到有人提到过这一点,但是指针的 const 向量允许您更改指针指向的对象,并且可以在需要时用作解决方法。跨度>