Is this a misuse of unique_ptr?

I am making the transition to smart pointers, and I'm trying to make sure that I use them correctly. There are many questions that cover when to use them, but I could not find the question specifically about getters.

I have a class to which the pointer belongs, and I want other classes to be able to access this pointer (Refactoring outdated code step by step). I wanted to give the class unique_ptr because it will own only this object, but they cannot be copied. Should I return a link to unique_ptr or just use 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();
+4
source share
4 answers

, , , A, shared_ptr.

, B A, unique_ptr.

, , . , .

, , , .

+6

B unique_ptr, pointer.get();. , , .

+5

unique_ptr shared_ptr?

.

- ? , . , A , unique_ptr .

( , unique_ptr null) , unique_ptr. , -. , unique_ptr, , unique_ptr .

+1
source

Returns a raw pointer or reference to the object that it points to. When an object matters std::unique_ptr, it indicates ownership. Meaning, an object containing a pointer will allocate and also delete allocated resources when they like it.

For instance:

class Car {
public:
  Engine* getEngine() const { return engine_.get(); }
private:
  std::unique_ptr<Engine> engine_;
}

You can ask for a car, perhaps an available engine, you should always assume that it may not be, but you should not free it, it is not yours, it belongs to the car.

0
source

Source: https://habr.com/ru/post/1681461/


All Articles