3
votes

I understood the concept of RAII (Resource acquisition is initialization). It basically says that resources should be reclaimed in destructor to avoid any memory leaks. But I didn't understand how shared_ptr is a type of RAII. Because shared_ptr doesn't guarantee that the pointer will be deleted at the end of the stack. Deletion is purely dependent on the counter. So how it is related to RAII?

1
It uses RAII to decrement the counter. When it hits zero, that particular destructor call will delete the object.Mysticial

1 Answers

6
votes

std::shared_ptr<T> extends RAII to resources with multiple ownership. Rather than having to figure out yourself when to delete a shared object, you take a shared pointer down, letting it destroy a shared object, but only when it is the last reference.

It is helpful not to think of the object pointed to by a shared pointer as an object owned by that shared pointer object. Instead, one could think of it as collectively owned by all shared pointers pointing to it. The resource acquired by the shared pointer object is not only the object itself, but also its reference counter. Releasing the object is an equivalent of decreasing the reference counter, with the caveat that once the reference count drops to zero, and additional operation of deleting the object must follow.