使用包含shared_ptr的对象的const正确性

tan*_*avo 7 c++ const shared-ptr

考虑对象:

class Obj
{
    public:
        Obj() : val(new int(1)) {}
        int& get() {return *val;}
        const int& get() const {return *val;}

    private:
        std::shared_ptr<int> val;
};
Run Code Online (Sandbox Code Playgroud)

正如所料,当构造对象并进行复制时,它们都可以通过Obj公开的shared_ptr修改相同的值.

    Obj nonconst1;
    Obj nonconst2(nonconst1);
    nonconst2.get() = 2;
    cout << nonconst1.get() << ", " << nonconst2.get() << endl;
Run Code Online (Sandbox Code Playgroud)

也可以const Obj从非const中复制构造一个对象,这似乎做了正确的事情,因为它允许读取而不是写入值 - 正如预期的那样,下面的代码会导致编译错误:

    const Obj const1(nonconst1);
    const1.get() = 3;
Run Code Online (Sandbox Code Playgroud)

但是,可以从const one复制构造非const Obj,然后允许修改该值.

    Obj nonconst3(const1);
    nonconst3.get() = 3;
Run Code Online (Sandbox Code Playgroud)

对我来说,这并不觉得是正确的.

有没有办法防止这种行为,同时仍然允许复制构造函数工作?在我的实际用例中,我仍然希望Obd的std容器成为可能.

Pup*_*ppy 1

不,没有,除非您想存储 a shared_ptr<const int>,在这种情况下没有人可以将其作为非常量访问。