I'm reading through Scott Meyers Effective C++ and I have a question regarding resource management. In the book, he suggests that one should use the auto_ptr object to manage memory as it will automatically call the destructor of the object it points to when it goes out of scope. Here is the example provided:
void f() {
Investment *pInv = createInvestment(); // Call factory function
... // use pInv
delete pInv; // release object
}
He claims that this is potentially problematic because there could be a number of things that happen in the ...
that would prevent the method from reaching delete pInv
(premature return statement, thrown exception, ...). This is the code that he suggests in its place
void f() {
std::auto_ptr<Investment> pInv(createInvestment()); // call factory function
... // use pInv as before
} // automatically delete pInv
This works because no matter what happens pInv
will be deleted when it goes out of scope.
My question is this: why wouldn't the destructor of pInv
be called when it goes out of scope in the first code block. Wouldn't a premature return statement push the object out of scope, or is that not how garbage collection works in C++?
Hopefully I have explained my confusion well enough. Thanks in advance!