I'm making the shift towards smart pointers, and I'm trying to make sure I use them properly. There are plenty of questions that cover when to use each one, but I wasn't able to find a question specifically about getters.
I have a class that owns a pointer, and I want other classes to be able to access that pointer (Refactoring legacy code in steps). I wanted to give the class a unique_ptr because it will only own that object, but they can't be copied. Should I be returning a reference to the unique_ptr, or just using a shared_ptr?
class B
{
public:
doAction() {};
};
class A
{
private:
std::unqiue_ptr<B> pointer;
public:
std::unique_ptr<B>& GetPointer()
{
return pointer;
}
};
a.GetPointer()->doAction();
If the other class needs to store the pointer and potentially lives longer than your class A, use a shared_ptr
.
If not, and your B
object should be destructed on destruction of A, this is a perfectly valid use of a unique_ptr
.
As pointed out in the comments, this only holds true if other classes are also allowed to change your pointer. If not, return a raw pointer.
The difference between both is not about who has access to the class, but about who is responsible for the destruction of the referenced object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With