You are on page 1of 8

Shared Pointers in C++

Usage & Implementation

What is a shared pointer?

Is a smart pointer
Smart pointers are class objects
Behaves like built-in pointers
Magic is that it manages objects that you create with new
You don't have to worry about when and whether to delete them
Smart pointers automatically delete the object at appropriate time

Working mechanism

Creating a shared pointer creates a shared object manager


Object manager has two attributes called shared count and weak count
Shared count is 1 and weak count is 0 for first pointer to an object
Shared count is incremented when Creating a new shared pointer with the same object
Assigning a shared pointer to an new shared pointer
Getting a new shared pointer from weak pointer with existing object

Working mechanism (continued)

Similarly weak count will increment when

Shared count will be decremented if

Creating new weak pointer from the object


Assigning to new weak pointer from another weak pointer of the same object
The variable go out of scope
The reset member function is called
Assigned a value of nullptr

Weak count will be decremented if

The variable go out of scope


The reset member function is called

Working mechanism (continued)

When the shared count is zero the managed object is destroyed by its
destructor call.
Object manager is destroyed when shared count and weak count both are
zero

Static pointer cast

static_pointer_cast of a shared_ptr creates another shared_ptr


static_pointer_cast checks for the compile time compatibility of the
objects
Opposite to dynamic_pointer_cast where a runtime check is performed for
type compatibility
We can downcast from a base object to derived object using
static_pointer_cast and the base class need not be polymorphic as with
dynamic_pointer_cast
This cast should be used when we know that the objects are compatible

Code example
std::shared_ptr<TestObject> obj1 = std::make_shared<TestChild>();
std::shared_ptr<TestChild> child1 = std::static_pointer_cast<TestChild>(obj1);
child1 = nullptr;
int test = 1;
if(test > 0) {
std::shared_ptr<TestObject> obj2 = obj1;
}
std::shared_ptr<TestObject> obj3 = obj1;
obj3.reset();
std::shared_ptr<TestObject> obj4 = obj1;
obj4 = nullptr;
obj3 = obj1;
std::weak_ptr<TestObject> wobj1(obj1);

Code example (continued)


if(test > 0) {
std::weak_ptr<TestObject> wobj2 = wobj1;
}
obj1 = wobj1.lock();
obj1 = nullptr;
obj3 = nullptr;
std::cout << "After all those operations!" << std::endl;
std::weak_ptr<TestObject> wobj3 = wobj1;
std::shared_ptr<TestObject> obj5 = wobj3.lock();
std::cout << "Getting shared pointer from weak pointer!" << std::endl;
if(obj5){
std::cout << "Object exists!" << std::endl;
}
else{
std::cout << "Object does not exists!" << std::endl;
}

You might also like