Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use shared_ptr or unique_ptr? [duplicate]

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?

like image 780
dziwna Avatar asked Feb 14 '13 09:02

dziwna


People also ask

Why would you choose shared_ptr instead of unique_ptr?

In short: Use unique_ptr when you want a single pointer to an object that will be reclaimed when that single pointer is destroyed. Use shared_ptr when you want multiple pointers to the same resource.

When should you use a shared_ptr?

An object referenced by the contained raw pointer will not be destroyed until reference count is greater than zero i.e. until all copies of shared_ptr have been deleted. So, we should use shared_ptr when we want to assign one raw pointer to multiple owners. // referring to the same managed object.

Is shared_ptr copy thread safe?

When you copy a std::shared_ptr in a thread, all is fine. At first to (2). By using copy construction for the std::shared_ptr localPtr, only the control block is used. That is thread-safe.

What happens when you copy a unique_ptr?

A unique_ptr does not share its pointer. It cannot be copied to another unique_ptr , passed by value to a function, or used in any C++ Standard Library algorithm that requires copies to be made. A unique_ptr can only be moved.


1 Answers

Short answer: depends.

It depends on if the pointer returned by getB may 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.

  • If the A still exists when you use the result of getB , you can store a unique_ptr and return a plain pointer (or a reference if getB can never return nullptr). That expresses "A owns B, and no-one else does".
  • If the A might go out of scope while you are using/holding the result of getB, but the B should go out of scope together with (or shortly after) the A, store a shared_ptr and return a weak_ptr.
  • If possibly many objects, including the callers of getB, may hold on to the B and there is no clear single owner, store and return shared_ptrs.
like image 60
Arne Mertz Avatar answered Sep 22 '22 15:09

Arne Mertz