I am trying to replace raw pointers with smart pointers.
class MyObj {
public:
MyObj() {
rawContainer = new BigObj();
}
const BigObj* GetRawObj() {
return rawContainer;
}
private:
BigObj* rawContainer;
};
When I call
auto rawObj = myObj.GetRawObj()
I avoid copying BigObj
and can only call the functions marked const, so I can't modify it's content.
class MyObj {
public:
MyObj() {
std::unique_ptr<BigObj> ptr(new BigObj());
container = std::move(ptr);
}
const std::unique_ptr<BigObj>& GetObj() {
return container;
}
private:
std::unique_ptr<BigObj> container;
};
This time, with auto smartObj = myObj.GetObj();
I can access non-const methods of smartObj
.
I understand the definition const std::unique_ptr<BigObj>& GetObj()
is making the reference constant, and not the underlying object, but changing it to const std::unique_ptr<const BigObj>& GetObj()
creates a compiler error.
Is there a sensible way to do this? I've seen suggestion of just returning a raw pointer from the smart pointer and using it like in the first example. The actual object in MyObj
can't be const since it can actually be modified by some methods.