Consider the object:
class Obj { public: Obj() : val(new int(1)) {} int& get() {return *val;} const int& get() const {return *val;} private: std::shared_ptr<int> val; };
As expected, when the object is designed and made copies, all of them can change the same value through shared_ptr, opened by Obj.
Obj nonconst1; Obj nonconst2(nonconst1); nonconst2.get() = 2; cout << nonconst1.get() << ", " << nonconst2.get() << endl;
It is also possible to copy-build the const Obj object from one of the non const, which seems to do the right thing, since it allows you to read, but not write to a value - as expected, the following code leads to a compilation error:
const Obj const1(nonconst1); const1.get() = 3;
However, you can copy-build a non-const Obj from const const, which then allows you to change the value.
Obj nonconst3(const1); nonconst3.get() = 3;
This does not seem const-correct to me.
Is there a way to prevent this behavior while still maintaining the ability to use the copy constructor? In my real use case, I still want Obj std containers to be possible.
tangobravo
source share