Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a misuse of unique_ptr?

Tags:

c++

c++11

c++14

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();
like image 568
Taztingo Avatar asked Dec 13 '22 22:12

Taztingo


1 Answers

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.

like image 71
Anedar Avatar answered Dec 31 '22 13:12

Anedar