What is the difference between shared pointer and unique pointer?

What is the difference between shared pointer and unique pointer?

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.

What is the use of unique pointer?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope.

How do I return a shared pointer?

So the best way to return a shared_ptr is to simply return by value: shared_ptr Foo() { return shared_ptr(/* acquire something */); };

How is a shared ptr different from a weak ptr?

With a shared_ptr, that something is the thing that contains the reference count. But with a unique_ptr, there is no reference count, so there is no thing that contains the reference count, thus nothing to continue to exist when the object is gone. So there’s nothing for a weak_ptr to refer to.

Why is a weak ptr not provided in the standard library?

I think that no one mentioned why standard library is not providing weak_ptr for unique_ptr. Weak pointer CONCEPT doesn’t disclaims unique_ptr usage. Weak pointer is only an information if the object has been already deleted so it’s not a magic but very simple generalized observer pattern.

Can You const _ cast things without shared ptr?

But people can also const_cast things; basic care and feeding of shared_ptr should provide reasonable quality of life for allocated objects who’s ownership must be shared. Then, there are weak_ptr s, which cannot be used in the absence of a shared_ptr.

How is shared _ ptr similar to garbage collection?

Like garbage collection, default use of shared_ptr encourages the programmer not to think about the contract between objects, or between function and caller. Thinking about correct preconditions and postconditions is needed, and object lifetime is just a tiny piece of that bigger pie.