On quinta-feira, 26 de abril de 2012 10.23.45, Stephen Bryant wrote: > Hi, > > > Naaaa, throwing from a constructor is fine. Throwing from a destructor > > is a big no no. Actually there is no other way to cleanly 'get out' > > when construction fails. > > Ooohh... big disagreement coming up here!! > > Consider this line: > > Foo *foo = new Foo(); > > Assuming 'new' succeeds and allocates memory on the heap: if the constructor > throws, the pointer 'foo' never gets initialised. > > How do you cleanly 'get out' of that one? I.e. how do you delete the > allocated memory without knowing where it is? If someone has a solution for > this, I'll happily change my position!
The solution is simple: nothing is required.
If the constructor throws, the language calls operator delete. There's no
leak. You can confirm by inspecting the assembly of the following program:
struct Foo { Foo(); };
Foo *f() { return new Foo; }
You'll notice that the body of the function f() contains at least one call to
operator delete().
> My opinion is that it is a question of design, and that any initialisation
> which throws on error must be performed post-construction in a separate
> step, such as foo->init() or so.
That's an opinion.
> Going back to Den's original post, that means he'd need to add an init
> method to ImageModel, and make sure it gets called when he wants to use the
> object.
In which case he doesn't need to throw to indicate an error.
--
Thiago Macieira - thiago.macieira (AT) intel.com
Software Architect - Intel Open Source Technology Center
Intel Sweden AB - Registration Number: 556189-6027
Knarrarnäsgatan 15, 164 40 Kista, Stockholm, Sweden
signature.asc
Description: This is a digitally signed message part.
_______________________________________________ Interest mailing list [email protected] http://lists.qt-project.org/mailman/listinfo/interest
