shared_ptr is a reference counted c++ 11 smart pointer which supports shared ownership model. reference counted means it keeps track of how many smart pointers are pointing to the dynamically created object ( manged object ).  The managed object is destroyed when reference count becomes zero.

shared_ptr and weak_ptr c++ tutorial

  • An empty shared_ptr does not own any resources and has no control block. control block holds the reference count.
  • we can copy or assign a shared_ptr to another shared_ptr.
#include <iostream>
#include <memory>
using namespace std;

class A
{
public:
  A ()
  {
  }
   ~A ()
  {
  }
};


int main ()
{
  shared_ptr < A > obj (new A); // ref count of obj is 1
  shared_ptr < A > pobj = obj; // obj and pobj shared 
                               //ownership of A
  
  return 0;
}

weak_ptr

weak_ptr does not control life time of the managed object.

Note: The article is yet to be completed.

Ref:

http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf



Related Contents to follow