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的OBJ。
Obj nonconst3(const1);
nonconst3.get() = 3;
對我來說這並不覺得const正確。
有沒有辦法來防止這種行爲,同時仍然允許複製構造函數工作?在我真正的用例中,我仍然希望Obj的std容器成爲可能。
也許,你應該定義複製構造函數採取非const引用,以避免複製'const'對象? – Nawaz 2013-04-30 08:34:17
@Nawaz,這樣做的工作(我沒有意識到可以在複製構造函數中使用非const引用)。不幸的是,我也希望const Obj能夠複製構建其他Const obj,但嘗試「Obj(const Obj&o)const'不能編譯 – tangobravo 2013-04-30 11:56:16