Function Return Technique

Hi, imagine I have the following code inside a function:

1
2
3
char* p = NULL;
if (!SomeOtherFunction(p)) return false;
delete p; return true;

If 'SomeOtherFunction' returns false so does the function and bypasses the rest of the code, meaning pointer 'p' doesn't get "cleared", yes? If so how can I do it so that all the DynMem gets deleted; not leaving any leaks? My first thought was to do the following but it seems a bit impractical:

1
2
3
bool result = true; char* p = NULL;
if (!SomeOtherFunction(p)) result = false;
delete p; return result;

I then tried using finally blocks but I found that C++ doesn't really support it. I read about Resource Acquisition Is Initialization (RAII) as a replacement, could that technique help me (don't really know what it is)? Any ideas for better code would be very much appreciated, or have I totally missed the point-er here? :)

EDIT: Additional Information: The function isn't in a class (so can't use a destructor if could be done); I don't want any global variables specifically for the function (i.e. to keep track of the allocated mem); and I would like it all taken care of in the function itself (if possible). ...Demands...Demands :)
Last edited on
1
2
std::auto_ptr<char> p;   // Defaults to 0 (NULL)
return SomeOtherFunction( p.get() );


I presume some other code exists between the declaration of p and
the call to SomeOtherFunction to initialize/allocate p, otherwise
SomeOtherFunction would have to initialize it and return it by taking
p by non-const reference. If that is the case, then SomeOtherFunction
would have to be changed to take a std::auto_ptr<> by non-const
reference (and then don't call it with p.get(); just p).

std::auto_ptr<> is declared in <memory>

std::auto_ptr<> may not be exactly what you want; from the looks
of it, you might be more interested in a boost::scoped_ptr, which
is declared in <boost/smart_ptr.hpp> but requires the boost libraries.


Thanx, I think using auto_ptr is the best way to go; I'll need to mod my code a little first. I didn't know about auto_ptr, and it looks to be a very useful class; simple too.

auto_ptr is ideal really as it's basically like an auto-signed variable in the fact that you don't have to worry about what the memory is doing (too much). Replacing auto_ptr with the pointer (+ some other stuff) seemed to solve my problem. Again Thanks. I've never heard of that Boost Library but #include <memory> did the job for me. :)
Topic archived. No new replies allowed.