Thursday 11 May 2017

CPP Smart Pointer

Smart Pointer

shared_ptr is a kind of Smart Pointer that is smart enough to automatically delete the associated pointer when its not used anywhere.Thus helps us to completely remove the problem of memory leaks and dangling Pointers.

  • When a new shared_ptr object is associated with a pointer,then in its constructor it increases the refernce count associated with this pointer by 1.
  • When any shared_ptr object goes out of scope then in its destructor it decrements the reference count of the associated pointer by 1. If reference count becomes 0 then it means no other shared_ptr object is associated with this memory, in that case it deletes that memory using “delete” function.
#include  // We need to include this for shared_ptr
 
int main()
{
std::shared_ptr p1(new int());
*p1 = 78;
std::cout<<"p1 = "<<*p1<<std::endl;
 
// Shows the reference count
std::cout<<"Reference count = "<<p1.use_count()<<std::endl;
 
// Second shared_ptr object will also point to same pointer internally
// It will make the reference count to 2.
std::shared_ptr p2(p1);
 
// Shows the reference count
std::cout<<"Reference count = "<<p1.use_count()<<std::endl;
 
if(p1 == p2)
{
std::cout<<"p1 and p2 are pointing to same pointer\n";
}
 
// Reset the shared_ptr, in this case it will not point to any Pointer internally
// hence its reference count will become 0.
p1.reset();
std::cout<<"p1 = "<<p1.use_count()<<std::endl;
 
// Reset the shared_ptr, in this case it will point to a new Pointer internally
// hence its reference count will become 1.
p1.reset(new int(11));
std::cout<<"p1 = "<<p1.use_count()<<std::endl;
 
// Assigning nullptr will de-attach the associated pointer and make it to point null
p1 = nullptr;
std::cout<<"p1 = "<<p1.use_count()<<std::endl;
 
if(!p1)
{
std::cout<<"p1 is NULL"<<std::endl;
}
return 0;
}

 

No comments:

Post a Comment