Smart pointers

There are two types of smart pointers. The unique pointer is a standard method which came from C++11 implementation that returns a pointer. A unique pointer does not to be shared by other parts of the code. To use any of smart pointer you have to include the memory header file into your program.

So you may mention that t is not necessary to work about delete operation. That’s why the unique pointer overcomes our problem about memory management.

But if you copy of a unique pointer, for instance, passing to another method as a parameter, causes a problem that it deletes actual pointer. So you can’t pass a unique pointer to another method directly. Of course std::move function which calls move constructor to help us call a function. But keep it in mind, if you call a move method you can’t reach the old value of actual pointer after return the function.

But there is a solution to it. Passing reference of pointer instates of itself.

On the other hand, the shared pointer is fine in many cases. Shared pointers hold an indicator counter and it increases it in every case of constructors and decreases it in each deconstruction calls. Shared pointer gives memory to the system back when there is no other copy in a complex operation.

So you don’t have to pass a pointer of the unique pointer to a method. At the same time, there is only one way, shared pointer, in the case of “has a” relation of two objects.

Weak Pointer

Shared pointer has two value, pointer and counter. The weak pointer indicates a pointer for the counter. And the weak pointer has two methods.

Expired is the method which returns a boolean value. If the shared pointers counter is 0 it’s expired.

The lock is the other method which returns a shared pointer of the pointer and increases the counter of it.

In circular reference, shared pointer causes a memory leak. We also use the weak pointer to avoid that.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *