Suppose we have the following code:
<Widget*> ( i = ; i < SOME_MAGIC_NUMBER; ++}
Widgets in the Code are a class. Obviously, this code segment may cause memory leakage. After the function is executed, every vwp element is destroy, but the Widget object we use is not deleted. Oh, no! Memory leakage!
Some people may want to talk about it. This is not simple. I will delete them and it will not be over. Add the following code at the end of the doSomething function:
( vector<Widget*>::iterator i = vwp.begin(); i != vwp.end(); ++*i;
However, is there any more elegant method for this situation? Maybe you can use the function object to accomplish this. It seems like a bit of high-end atmosphere:
DeleteObject { template<typename T> ()( T* ptr) <SpecialString*>
}
This method looks good, and we have released the pointer elegantly. But is there no better way? The good news always comes late, and the smart pointer comes on stage. In the C ++ 11 standard, the smart pointer is located in the header file of the std namespace <memory>, you need to add related statements when using them (Here we use cmd_ptr ):
#include <memory> std::shared_ptr;
The preceding problem can be solved as follows:
<Widget> SPW;
vector<SPW> ( i = ; i < SOME_MAGIC_NUMBER; ++ Widget));
...
}
Thank you for reading this article. I hope it will help you!
Published by Windows Live Writer.