Re: releasing resources allocated for a particular object
ssylee <stanigator@gmail.com> kirjutas:
For example, I have a BITMAPINFO* and a BYTE* object to release the
resources. Would the most bulletproof way of doing so involve checking
to see if they are null, then if they are not, invoke a free()
function call on that and make sure that they point to null?
In case of C-style interfaces which require releasing of resources I have
found Alexandrescu's ScopeGuard quite convenient (look it up in net). The
usage goes like this (for malloc()/free() it is very similar):
#include <ScopeGuard/ScopeGuard.h>
// ...
// call some C-style interface
addrinfo* res;
int k =getaddrinfo(server.c_str(), str(port).c_str(), NULL, &res);
// check the result; if failed, just return (the resource is
// not allocated and thus there is no need to release it):
if (k!=0) {
throw std::runtime_error("Cannot resolve server name");
}
// Set up a ScopeGuard which will release
// the resource when exiting the function.
// The ON_BLOCK_EXIT macro is part of the ScopeGuard utility.
ON_BLOCK_EXIT(freeaddrinfo, res);
// rest of the function...
Note that by releasing there is no need to check that the resource handle
is valid as it has been checked already before, neither is there any need
for setting the resource handle to NULL or anything else.
hth
Paavo