I have a question about std::unique_ptr and std::shared_ptr. I know there are loads of questions about when to use which one, but I’m still not sure if I understand it correctly. I read somewhere that the default choice for smart pointer should be std::unique_ptr, but as I understand it, for my needs I should rather use std::shared_ptr. For example, I have:
class B;
class A
{
private:
B* b;
public:
B* getB();
};
A::getB()
{
return b;
}
So basically class A owns pointer to object of type B and there’s a method which returns this pointer. If I create getter, I assume that some other class can access this pointer and therefore it should be shared_ptr instead of unique_ptr. Am I right, or I don’t get it yet?
Short answer: depends.
It depends on if the pointer returned by
getBmay be stored/used somewhere while the owning A has gone out of scope. The difference is about ownership not about how many pointers you do have.getB, you can store aunique_ptrand return a plain pointer (or a reference ifgetBcan never returnnullptr). That expresses “A owns B, and no-one else does”.getB, but the B should go out of scope together with (or shortly after) the A, store ashared_ptrand return aweak_ptr.getB, may hold on to the B and there is no clear single owner, store and returnshared_ptrs.