Smart pointer_application

Let's look at shared_ptr's applications and problems we are often faced with.

There are beautiful examples in data structure such as linked-list and tree. In this post, we will take tree example. Before learning shared_ptr, it is common to use normal pointer to save children node's information.


When taking tree structure, we can use shared_ptr instead of normal pointer since every node is usually allocated in heap memory.


Advantage, when using shared_ptr, is ofcurse automatic memory releasing. In existing tree structure, Node class should be deleted from high level(or leaf node). So we create wrapping class called 'tree' and use postorder algorithm to release memory.
However Node class ,used with shared_ptr, doesn't need wrapper one and also dose not need to do anything in destructor. Memory will be released automatically in an ordered way. For example, when node is deleted, deleting shared_ptr also follows. Then, shared_ptr's destructor makes memory that is indicated by ptr be released. If there is no other shared_ptr indicating the same memory, all the node will be deleted in an ordered way. This is beautiful one that can fully show andvantages of smart pointer.

Be cautious.
As we have seen previous post of smart pointer, you shouldn't make smart pointer indicate stack memory. If you do mistakes like that, memory might be released unintentionally and you lose information of subsequent node.
So, when we want to store nodes information which are allocated in stack, it is needed to make copy of it in heap memory. This makes another but same information that isn't necessary.


This code shows way to use stack memory objects in smart-pointer. The point of this code is that when trying to insert new Tree(or node), since smart-pointer shouldn't save stack address, it is necessary to use 'make_shared' method for copying object in heap. At the end, the computer has twice of same information objects. One is in stack, and another in heap.
It's unnecessarily complicated for caring memory. If you want to delete stack object that you will not use anymore, so that you prevent unnecessary memory duplication,

This way may help you. Since we want to remove information stored in stack, we should use stack object in scope as possible as we can. But this doesn't look good at a glance and caring memory ourselves doesn't fit with purpose of smart pointer.

The problem which is relevant to smart-pointer always occur when trying to care stack memory information. It is much better to allocate memory in heap when you don't want to use object only inside the scope. Especially, when duplicate same information in heap, If size of the object is large, It will cost long duplicate overhead time and large memory space. we should considerably decide and study where we should allocate object in. 
need Heap? or just Stack.

Comments