开发者

shall I delete smart pointer manually?

This might be a dumb question but I'm just not sure about the answ开发者_如何学运维er. The following code read a file, and for each line of the file, a smart pointer is created by "new". If the smart pointer will be used in the future, it's stored in a list, otherwise it's not stored.

My question is that: if the smart pointer is not stored, will that cause potential memory leak? Thank you.

int main(){
    .....;
    std::list<SomeClass> aList;
    while(inFile >> ss){
         std::tr1::shared_ptr<SomeClass> aPtr(new SomeClass());
         //do something in foo(aPtr) to aPtr, 
         //if aPtr will be used later, then it's stored in aList
         //otherwise, it's not stored
         foo(aPtr);
    }
    .....;
}


As long as you're storing it with a copy of the smart pointer, this will not leak memory. When the aPtr object falls off the stack (at the end of each while loop execution), it will be destroyed. If it is the only holder to the allocated object, it will delete it. But if you stored a copy of aPtr elsewhere, then it is not the only holder to the allocated object, and it will not delete it.


No memory leaks shall ensue!

why? because smart pointers are... smart, they have the automatic cleanup feature which is great, because it prevents elusive bugs like memory leaks.

Thus for smart pointers you do not need to explicitly delete the pointer.


No memory leak can be caused, because the shared_ptr will deallocate the allocated object when it goes out of scope.


When an pointer is assigned to a smart pointer, a reference counter related to the pointer is increased by one (the reference counter is 0 when the pointer has not been assigned to any smart pointer). When a smart pointer goes out of scope and is deleted, then the reference counter for the pointer tracked by the sp is decreased by one: eventually the memory referenced by the pointer is deleted when the reference counter goes back to 0.

In your case, if the object SomeClass is assigned only to aPtr, then maybe an auto pointer will do the job with a slightly less overhead. However, if you declare the list as std::list<std::tr1::shared_ptr<SomeClass> > then you could avoid copying SomeClass (only the reference counter to the object will be increased) and take full advantage of the smart pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜