Delete deleted pointer manually?

This may be a stupid question, but I'm just not sure about the answer. The following code reads the file, and for each line in the file, a smart pointer is created "new." If the smart pointer will be used in the future, it will be saved in the list, otherwise it will not be saved.

My question is: if the smart pointer is not saved, will it cause a potential memory leak? Thanks.

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 stored in aList //otherwise, it not stored foo(aPtr); } .....; } 
+4
source share
4 answers

As long as you store it with a copy of the smart pointer, this will not lead to a memory leak. When the aPtr object falls off the stack (at the end of each execution of the loop), it will be destroyed. If he is the sole owner of the selected object, he will delete it. But if you saved a copy of aPtr in another place, then this is not the only holder of the selected object, and it will not delete it.

+6
source

There will be no memory leaks!

why? because smart pointers ... smart, they have an automatic cleanup feature that is great because it prevents elusive errors like memory leaks.

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

+3
source

A memory leak cannot be caused, since shared_ptr will free the allocated object when exiting it.

0
source

When a pointer is assigned to a smart pointer, the reference counter associated with the pointer is incremented by one (the reference counter is 0 when no smart pointer was assigned to the pointer). When the smart pointer goes out of scope and is deleted, the reference counter for the pointer tracked by sp decreases by one: in the end, the memory referenced by the pointer is deleted when the reference counter goes back to 0.

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

0
source

All Articles