0

I am a novice in c++. I have come across the usage of std::unique_ptr and std::shared_ptr in my code

typedef std::unique_ptr<type1> type1Handler;
typedef std::shared_ptr<type2> type2Handler;

I have two questions:

  1. What is the advantage of using unique_ptr and shared_ptr
  2. What is the prime difference among them?

Possibly an example would be much helpful!

SKPS
  • 4,404
  • 3
  • 21
  • 50

2 Answers2

7

They are for 2 completely different use cases.

  1. std::unique_ptr retains sole ownership of an object and destroys that object when the unique_ptr goes out of scope. No two unique_ptr's instances can manage the same object. (http://en.cppreference.com/w/cpp/memory/unique_ptr)

  2. std::shared_ptr retains shared ownership of an object. Several shared_ptr objects may own the same object. The object is destroyed and its memory deallocated when the last remaining shared_ptr owning the object is destroyed or the last remaining shared_ptr owning the object is assigned another pointer via operator= or reset(). (http://en.cppreference.com/w/cpp/memory/shared_ptr)

To enforce the sole ownership std::unique_ptr is non-assignable and non-copyable. This means you have to use move semantics with it.

If you see the unique_ptr somewhere in the code this means that Look, here is the pointer and we own it!. This cannot be said about shared_ptr, where ownership can be dispersed all around the code.

Sergey K.
  • 23,426
  • 13
  • 95
  • 167