Re: when to call auto_ptr release?
George wrote:
Secondly, and that makes this
solution even worse, it would be really hard to get this to work in the
presence of exceptions.
If we pass the return value of get() of auto_ptr to function f, the
resorce is still managed by auto_ptr and dues to RAII pattern, no resource
leak.
If we pass the return value of releas() of auto_ptr to function f, the
resource becomes a raw resource, and there will be resource leak if there
are exceptions.
Now I am confused what do you mean "hard to get this to work in the
presence of exceptions.", and it is appreciated if you could provide more
description about what do you mean?
With exceptions, the function I was referring to could return 'true',
'false' or throw an exception. Think about how these three cases complicate
the use of the function.
Thirdly, it clutters the code using this with
checks if ownership was transferred.
Could you show me how clutter the resulted code will be if we use the
function suggested by Doug? I can not understand why you mean it is
clutter, just check some return values. :-)
See dict.org for a definition of the term clutter.
Anyway, the point is this:
1. You start of with an idea, just like you would describe it to someone:
do this
do that with the result
do something else
2. Then, you start coding:
tmp = do_this();
do_that(tmp);
do_something_else();
Up to this point, you should be able to see the initial idea directly
reflected in the sourcecode.
3. Then, using e.g. C which doesn't support exceptions and RAII, you start
adding error handling:
tmp = do_this();
if(!tmp)
return EFAILED;
int e1 = do_that(tmp);
if(e1 != NO_ERROR) {
free(tmp);
return e1;
}
int e2 = do_something_else();
if(e2 != NO_ERROR) {
free(tmp);
return e2;
}
free(tmp);
return NO_ERROR;
Now, this doesn't look like the original at all, right? The simple reason is
that it's cluttered with error-handling code which obscures the logic
behind that. It is useful to avoid such code.
Uli
--
C++ FAQ: http://parashift.com/c++-faq-lite
Sator Laser GmbH
Gesch??ftsf??hrer: Michael W??hrmann, Amtsgericht Hamburg HR B62 932