What is the difference between shared PTR and Unique_ptr?
Table of Contents
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.
The std::unique_ptr and std::shared_ptr are smart-pointers. An std::unique_ptr owns an object exclusively, whereas the ownership of an object can be shared via std::shared_ptr instances. One of the helpful features of unique_ptr is that it can be seamlessly converted to a compatible shared_ptr.
When should you use Unique_ptr?
When to use unique_ptr? Use unique_ptr when you want to have single ownership(Exclusive) of the resource. Only one unique_ptr can point to one resource. Since there can be one unique_ptr for single resource its not possible to copy one unique_ptr to another.
Is Unique_ptr Atomic?
No there no standard atomic functions for std::unique_ptr .
Can Unique_ptr be null?
Nullability – a scoped_ptr or unique_ptr can be null, a value object can never be. Polymorphism – a value object is always exactly its static type, but you can substitute in different derived types for a unique_ptr. The previously-held object is automatically destroyed when you do this.
Is Unique_ptr thread safe?
unique_ptr is thread safe when used correctly. You broke the unwritten rule: Thou shalt never pass unique_ptr between threads by reference. The philosophy behind unique_ptr is that it has a single (unique) owner at all times.
Is Weak_ptr thread safe?
Note that the control block used by std::weak_ptr and std::shared_ptr is thread-safe: different non-atomic std::weak_ptr objects can be accessed using mutable operations, such as operator= or reset , simultaneously by multiple threads, even when these instances are copies or otherwise share the same control block …
Can we delete Unique_ptr?
An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don’t have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.