C++ Smart Shared Pointer

Introduction

We can have multiple pointers point to a single object.

We can say that all of them own our pointed-to object, that is, our object has shared ownership.

And only when last of those pointers get destroyed, our pointed to object gets deleted.

This is what a shared pointer is for.

Multiple pointers pointing to a single object, and when all of them get out of scope, the object gets destroyed.

Shared pointer is defined as std::shared_ptr<some_type>.

It can be initialized using the std::make_shared<some_type>(some_value) function.

Shared pointers can be copied.

To have three shared pointers pointing at the same object we can write:

#include <iostream> 
#include <memory> 

int main() 
{ 
    std::shared_ptr<int> p1 = std::make_shared<int>(123); 
    std::shared_ptr<int> p2 = p1; 
    std::shared_ptr<int> p3 = p1; 
} 

When all pointers get out of scope, the pointed-to object gets destroyed, and the memory for it gets deallocated.




PreviousNext

Related