Monday, April 24, 2017

What is Smart Pointer

Smart pointer is a class which wraps raw C++ pointers with some additional functionality, e.g. automatic memory de-allocation, reference counting etc.

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
 Type of smart pointers and usage:
  • Use std::unique_ptr when 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_ptr when 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_ptr when 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 or std::auto_ptr except in special cases which you can read up on if you must.


No comments:

Post a Comment