"Michael Klatt" <md*****@ou.edu> wrote in message
news:2c**************************@posting.google.c om...
class ResourceHandle
{
public :
ResourceHandle(T* ptr) { /* take ownership of T* */ }
~ResourceHandle() { /* release T* resource */ }
};
ResourceHandle f() { /* return a new T* */ }
Function f() relies on ResourceHandle(T*) being called as a result of
the return statement to avoid a resource leak. But what happens if
the return value of f() is not used in the calling function?
int main()
{
ResourceHandle resource(f()); // no leak
f(); // resource leak if return statement is elided?
}
Even if the result of evaluating f() is not used in any other way, it will
still be destroyed.
However, your program may have a serious problem. Your class ResourceHandle
does not have a copy constructor, which means that when you copy a
ResourceHandle object, doing so implicitly copies its members. Now consider
this:
ResourceHandle f()
{
ResourceHandle res;
// Do something here that gives a value to result
return res;
}
When f exits, res will be copied to serve as the return value and then
destroyed. Whatever resource res refers to will presumably be freed. Now,
on the caller's side:
f();
f returns a result that is put in a compiler-generated temporary and then
destroyed. That result is a copy of the local variable named in function f.
When the result is destroyed, the resource to which it refers is
freed--presumably for the second time.
I suspect that behavior is not what you have in mind.