Motivation
In recent days, I just dabbed into the area of resource management in C++, and after going through the tiresome recycle the resource using manual delete each time when we finished the functionality. I came acrross the magical attribution of the local variable———it can recyle the resource at some certain occassions, so I utilized which to free me from a lot of meaningless “delete” code(Through writing delete instruction do helpe me gain the whole picture of the program).
Just two weeks later, I talked with one of my friends about my (so-called) best practice of resource management. He just told me the fact that what I did is just a minor subset that the smart pointer published in C++11. Then I decided to take some notes in it, just to be a little closer to the goal mastering the C++(doge). After a quick browsering of the textbook& blog& manual provided on the Internet, I have a rough idea of what is it and how to use it, but without practicing in the real industry project. I still feel very uneasy about the detail of it, like the sentences that is haunting around my mind: “what I cannot create, I do not understand.“ So I decided to create my our wheel, maybe ugly, but which is so meaningful to my career.
Devil is in the details
In the rest of the passage, I will introduce a naive smart implementation of smart pointer.
1 |
|
The whole picture seems very great, but if we are more careful, we can detect some issues:
1.Since the increment and decrement of reference count requires atomicy, the high frequency may slow down the performance in the concurrent circumstances.
2.The latent leakage of memory will occur in some special cases, since the relationship between smart pointer and targeted object is tight-binded, so the cycle reference will be a huge disaster to the whole system. We have am example below:
1 |
|
In this scenario, we need to introduce the weak_ptr. The weak_ptr will not modify the target object’s rc.
The next wheel to create must be the unique_ptr(In fact it is much more easy to implement than shared_ptr).
1 | template<typename T> |