Smart pointers should be preferred over raw pointers because it could help in overcoming some limitation of raw pointers such as memory leak, dangling pointers etc.
Let's take below example -
MyObject *p = new MyObject();
p->func(); // Use the object in some way.
delete p; //Destroy the object.
Now, create the same as smart pointer -
std::unique_ptr<MyObject> p(new MyObject());
p->func(); // Use the object in some way.
//No Need to worry about deleting the pointer
Some of the usage of smart pointers are -
- Protecting Against Exceptions
- Holders, (note, std::auto_ptr is implementation of such type of smart pointer)
- Resource Acquisition Is Initialization (This is frequently used for exception-safe resource management in C++)
- Holder Limitations
- Reference Counting
- Concurrent Counter Access
- Destruction and De-allocation
- Use
std::unique_ptrwhen you don't intend to hold multiple references to the same object. For example, use it for a pointer to memory which gets allocated on entering some scope and de-allocated on exiting the scope. - Use
std::shared_ptrwhen you do want to refer to your object from multiple places - and do not want it to be de-allocated until all these references are themselves gone. - Use
std::weak_ptrwhen you do want to refer to your object from multiple places - for those references for which it's ok to ignore and deallocate (so they'll just note the object is gone when you try to dereference). - Don't use the
boost::pointers orstd::auto_ptrexcept in special cases which you can read up on if you must.
No comments:
Post a Comment