【发布时间】:2013-04-24 02:28:19
【问题描述】:
考虑对象:
class Obj
{
public:
Obj() : val(new int(1)) {}
int& get() {return *val;}
const int& get() const {return *val;}
private:
std::shared_ptr<int> val;
};
正如预期的那样,当构建对象并制作副本时,它们都可以通过 Obj 暴露的 shared_ptr 修改相同的值。
Obj nonconst1;
Obj nonconst2(nonconst1);
nonconst2.get() = 2;
cout << nonconst1.get() << ", " << nonconst2.get() << endl;
也可以从非 const 之一复制构造 const Obj 对象,这似乎是正确的,因为它允许读取但不能写入该值 - 正如预期的那样,以下代码会导致编译错误:
const Obj const1(nonconst1);
const1.get() = 3;
但是,可以从 const 复制构造一个非 const Obj,然后允许修改该值。
Obj nonconst3(const1);
nonconst3.get() = 3;
对我来说,这感觉不正确。
有没有办法防止这种行为,同时仍然允许复制构造函数工作?在我的实际用例中,我仍然希望 Obj 的 std 容器成为可能。
【问题讨论】:
-
也许,你应该定义复制构造函数采用非常量引用以避免复制
const对象? -
@Nawaz,这确实有效(我没有意识到可以在复制构造函数中使用非常量引用)。不幸的是,我也希望 const Obj 能够复制构造其他 Const obj 但尝试
Obj(const Obj& o) const不会编译
标签: c++ constants shared-ptr