Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shall I delete smart pointer manually?

This might be a dumb question but I'm just not sure about the answer. 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);
    }
    .....;
}
like image 238
EXP0 Avatar asked Jul 13 '11 19:07

EXP0


People also ask

Do I need to delete smart pointer?

There is no need to delete it yourself. By design, there is even no way to delete the object yourself directly, as this might result in some dangling pointers and inconsistencies. unique_ptr are another kind of smart pointers.

Should you always delete a pointer?

Also when you access freed memory you can't guarantee that the data that is returned to you is the data you wanted/expected, so you should only do delete pointers in the destructor of their owner or when you are sure that you won't need them anymore.

What is a smart pointer and why it is needed?

A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.

What happens when we delete pointer?

The address of the pointer does not change after you perform delete on it. The space allocated to the pointer variable itself remains in place until your program releases it (which it might never do, e.g. when the pointer is in the static storage area).


2 Answers

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.

like image 83
Nicol Bolas Avatar answered Oct 18 '22 16:10

Nicol Bolas


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.

like image 21
rrazd Avatar answered Oct 18 '22 15:10

rrazd