What are smart pointers?

It is one of the smart pointers provided by the Boost.SmartPointer library. Smart Pointers basically provide automatic memory management. When a smart pointer is no longer in use, that is when it goes out of scope, the memory it points to is deallocated automatically. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time.

The objects of smart pointer class look like pointer, but can do many things that a normal pointer can't like automatic destruction.

Various important properties of smart pointers :-
  1. no ownership at all.
  2. transfer of ownership.
  3. share of ownership.
What is shared_ptr?

boost::scoped_ptr is much more similar to boost::scoped_ptr. The key difference between both of them is that shared_ptr is not necessarily the exclusive owner of an object. Ownership can be shared with the with other smart pointers of type boost::shared_ptr. The shared object is not released until the last copy of the shared pointer referencing the object is destroyed.

How to construct a shared_ptr?

boost::shared_ptr<int> p1{new int {1}};

#include <boost/shared_ptr.hpp>                                    // header file used for including shared_ptr
#include <iostream>
using namespace std;

int main()
::shared_ptr<int> p1{new int{1}};                               //syntax for constructing a shared_ptr

cout << *p1 << '\n';                                                              //printing the value hold by shared_ptr 1   boost::shared_ptr<int> p2{new int{p1}};                          //syntax for initialising a shared_ptr 2 with another shared_ptr 1   cout << *p2 << '\n';                                                              //printing the value hold by shared_ptr 1
.reset(new int{2});                                                           //resetting our pointer 2 and re-intialising it with 2

cout << *p2<< '\n';                                                               //printing the value hold by shared_ptr 2

return 0;



1 2