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);
}
.....;
}
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With