What are the equivalent uses of each smart pointer in comparison to similar (but not limited to) some advanced techniques using raw pointers?
My understanding is minimal, but from what I can gather:
std::shared_ptr::reset
the underlying deallocator
is called.std::shared_ptr
that does not increment the reference count and is invalidated when its parent std::shared_ptr
no longer exists. May return and invalid reference. Always check before using.RAW POINTER EQUIVALENT EXAMPLES
Reference counting, cache implementations: std::map<std::string, std::pair<long, BITMAP*> > _cache;
Singletons with transfer of ownership:
class Keyboard { public: //... static Keyboard* CreateKeyboard(); ~Keyboard(); //... private: //... Keyboard(); static Keyboard* _instance; //... };
Aggregate Containers, no ownership: Spatial partitioning graphs and trees, iterative containers, etc.
Composite Containers, ownership: Large objects.
--EDIT--
As I am working I came upon an interesting case, DeadMG pointed out that smart pointers are supposed to be used as easy abstractions to take care of resource management; what about file-scope objects that can not be created on the heap at the point of declaration but instead must be created at a later time?
The only difference between weak_ptr and shared_ptr is that the weak_ptr allows the reference counter object to be kept after the actual object was freed. As a result, if you keep a lot of shared_ptr in a std::set the actual objects will occupy a lot of memory if they are big enough.
unique_ptr is a new facility with a similar functionality, but with improved security. auto_ptr is a smart pointer that manages an object obtained via new expression and deletes that object when auto_ptr itself is destroyed.
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.
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. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.
what idiom is each smart pointer supposed to replace?
Every single one of them, ever, that eventually involved destroying the pointed-to resource. So in other words, virtually all of them. I can think of no idioms involving raw pointers that did not involve destroying a pointed-to resource. Every other use isn't really an idiom, it's just "Using a pointer".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With