Re: Possible memory leak when constructing an object from a new expression?
"Richard Smith" <richard@ex-parrot.com> schrieb im Newsbeitrag
news:97cd4222-9cb6-404a-8288-1f4dd92182c8@k3g2000prl.googlegroups.com...
On Apr 19, 12:50 am, "Matthias Hofmann" <hofm...@anvil-soft.com>
wrote:
TFoo&
TFoo::operator=(const TFoo& that)
{
if (this != &that) {
auto_ptr<TBar> bar1 = new TBar(*that.fBar1);
auto_ptr<TBar> bar2 = new TBar(*that.fBar2);
TSuperFoo::operator=(that);
fBar1 = bar1;
fBar2 = bar2;
These assignments don't compile as auto_ptr doesn't convert to a raw
pointer. They should probably read:
delete fBar1; fBar1 = bar1.release();
delete fBar2; fBar2 = bar2.release();
... Unless, of course, the data members have been changed to auto_ptrs
too.
Yes, I just took a look at the original article and found out that the
author in fact redefines TFoo for the above mentioned assignment operator to
work:
class TFoo : public TSuperFoo {
auto_ptr<TBar> fBar1;
auto_ptr<TBar> fBar2;
// method definitions...
};
I oversaw that in my original post, sorry for the confusion.
The constructor of std::auto_ptr is not permitted to throw an
exception. The standard is quite clear on that point. However,
supposing you'd used a shared_ptr instead (whose constructor can in
some circumstances throw exceptions), the standard then guarantees
that the constructor will temporarily catch that exception, delete the
raw pointer argument, and rethrow, thus ensuring that no memory leak
occurs.
That's good news, but is the boost library already part of the standard? I
only know about the 03 version of the standard, and as far as I know, there
is no shared_ptr in it.
X( T* ptr )
try : data( allocate_data() ), p(ptr) {
/* function body */
} catch (...) {
delete ptr;
}
The syntax for the latter is a bit peculiar, but if it's necessary to
handle an exception from a initialiser, this is sometimes the only way
of doing it. (This is because it's not always possible to rearrange
the function so the exception is raised in the main body of
constructor. For example, references and constant members must be
initialised in the initialiser list, and sometimes their
initialisation may throw exceptions.)
This is the second time in my life that I heard about function try blocks,
but I have never bothered much with exceptions. But anyway, this answer my
question about memory leaks when constructing an object from a new
expression.
--
Matthias Hofmann
Anvil-Soft, CEO
http://www.anvil-soft.com - The Creators of Toilet Tycoon
http://www.anvil-soft.de - Die Macher des Klomanagers
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]