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);
}
.....;
}
As long as you’re storing it with a copy of the smart pointer, this will not leak memory. When the
aPtrobject 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 ofaPtrelsewhere, then it is not the only holder to the allocated object, and it will not delete it.