473,320 Members | 1,881 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Exception in constructor calls destructor????

JAL
According to MSDN2, if a managed class throws an exception in the
constructor, the destructor will be called. If an exception is thrown in the
constructor the object never existed so how in the world can the destructor
of a object that does not exist get called!

Here is the MSDN2 document:

Code authored in Visual C++ and compiled with /clr will run a type's
destructor for the following reasons:
....
If an exception is thrown during the object's construction.
....

So for an exception is thrown in a "Parrot" class constructor:

"He's not pining! He's passed on! This Parrot is no more! He has ceased to
be! He's expired and gone to meet his maker! He's a stiff! Bereft of life, he
rests in peace! If you hadn't nailed him to the perch he'd be pushing up the
daisies! His metabolic processes are now history! He's off the twig! He's
kicked the bucket, he's shuffled off his mortal coil, run down the curtain
and joined the bleedin' choir invisible! This is an ex-Parrot!"

Which leads to:

Q: What does emitting an exception from a constructor mean?

A: It means that construction has failed, the object never existed, its
lifetime never began. Indeed, the only way to report the failure of
construction -- that is, the inability to correctly build a functioning
object of the given type -- is to throw an exception.

In biological terms, conception took place -- the constructor began --, but
despite best efforts it was followed by a miscarriage -- the constructor
never ran to term(ination).

Incidentally, this is why a destructor will never be called if the
constructor didn't succeed -- there's nothing to destroy. "It cannot die, for
it never lived." Note that this makes the phrase "an object whose constructor
threw an exception" really an oxymoron. Such a thing is even less than an
ex-object... it never lived, never was, never breathed its first. It is a
non-object.

So how do we rationalize calling the destructor in C++/cli when an exception
is thrown in the constructor?

Jan 1 '06 #1
8 1774
> According to MSDN2, if a managed class throws an exception in the
constructor, the destructor will be called. If an exception is thrown in
the
constructor the object never existed so how in the world can the
destructor
of a object that does not exist get called!
In clr object starts its life when its memory is allocated and initialized
(by the runtime). In this sence constructor is just secondary initializer.
Which leads to:

Q: What does emitting an exception from a constructor mean?

A: It means that construction has failed, the object never existed, its
lifetime never began. Indeed, the only way to report the failure of
construction -- that is, the inability to correctly build a functioning
object of the given type -- is to throw an exception.


The fact that object did not finish its construction does not mean it never
existed.
--
Vladimir Nesterovsky
Jan 1 '06 #2
JAL
"Vladimir Nesterovsky" wrote:
In clr object starts its life when its memory is allocated and initialized
(by the runtime). In this sence constructor is just secondary initializer.
The fact that object did not finish its construction does not mean it never existed.


This looks like Objective Cs id myInstance= [[MyClass alloc] init];
The fact that object did not finish its construction does not mean it never
existed.


You would have to argue with Herb Sutter about that one:

"An object's lifetime begins when its constructor completes.
Corollary: An object whose constructor did not complete never existed.
Corollary: The only way to report a failed construction is to exit the
constructor by means of an exception.
...."
Jan 1 '06 #3
JAL wrote:
"Vladimir Nesterovsky" wrote:
The fact that object did not finish its construction does not mean
it never existed.


You would have to argue with Herb Sutter about that one:

"An object's lifetime begins when its constructor completes.
Corollary: An object whose constructor did not complete never existed.
Corollary: The only way to report a failed construction is to exit the
constructor by means of an exception.
..."


That's true for standard C++, but it's not true for the CLR. for better or
worse.

-cd
Jan 1 '06 #4
but that also means that in a destructor of a managed class you can't be
sure anymore that your object is initialized properly?

kind regards,
Bruno.

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:OQ****************@TK2MSFTNGP11.phx.gbl...
JAL wrote:
"Vladimir Nesterovsky" wrote:
The fact that object did not finish its construction does not mean
it never existed.


You would have to argue with Herb Sutter about that one:

"An object's lifetime begins when its constructor completes.
Corollary: An object whose constructor did not complete never existed.
Corollary: The only way to report a failed construction is to exit the
constructor by means of an exception.
..."


That's true for standard C++, but it's not true for the CLR. for better
or worse.

-cd

Jan 1 '06 #5
Bruno van Dooren wrote:
but that also means that in a destructor of a managed class you can't
be sure anymore that your object is initialized properly?


Yes and no.

For a managed class, the object is fully initialized by the CLR before the
ctor-initializer-list begins. All fields are initialized to their 'natural'
values - int are 0, references are null, bools are false, etc.

As Vladmir responded earlier, the ctor is really just a secondary
initializer.

-cd
Jan 1 '06 #6
"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote
but that also means that in a destructor of a managed class you can't
be sure anymore that your object is initialized properly?


Yes and no.

For a managed class, the object is fully initialized by the CLR before the
ctor-initializer-list begins. All fields are initialized to their
'natural' values - int are 0, references are null, bools are false, etc.

This initialization includes the vtables, too. I.e. during the
explicitly coded construction (base & member ctors),
the object's dynamic type is always that of the most-derived
object. This in turn introduces problems with destroying
a partially constructed object. For instance, consider
the base class ctor succeeds but one of the member
ctors throws. There's no reliable way to invoke (only)
the destructor of the base class.

Additionally, it's probably well worth mentioning that MS's
point of view is that object destruction of managed objects
follows the Disposable pattern. That means your objects
should be prepared to handle multiple calls of the
destructor (because it's apparently not considered invalid
to call Dispose more than once on a given object).

I'd tend to say you simply have to forget the standard
C++ object lifetime & construction model.

At the risk of repeating myself, I don't think it's exactly
great design ...

-hg
Jan 1 '06 #7
Ok i get your meaning. i thought you meant that the destructor would be
called if an exception was thrown during the construction phase.

kind regards,
Bruno.
"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:ez**************@TK2MSFTNGP14.phx.gbl...
Bruno van Dooren wrote:
but that also means that in a destructor of a managed class you can't
be sure anymore that your object is initialized properly?


Yes and no.

For a managed class, the object is fully initialized by the CLR before the
ctor-initializer-list begins. All fields are initialized to their
'natural' values - int are 0, references are null, bools are false, etc.

As Vladmir responded earlier, the ctor is really just a secondary
initializer.

-cd

Jan 1 '06 #8
JAL
Carl.... I think that this type of non standard behaviour needs to be
explicitly pointed out to the unsuspecting coder who, IMHO, coming from C++
rightfully assumes that the destructor will not be called if an exception is
thrown in the user written constructor. I can easily think of examples where
this can cause trouble such as doing IncrementRefCount in the constructor and
DecrementRefCount in the destructor. It would then be possible to throw an
exception without a successful call to IncrementRefCount in the constructor
and then call DecrementRefCount on exception leaving the system in an invalid
state.

"Carl Daniel [VC++ MVP]" wrote:
That's true for standard C++, but it's not true for the CLR. for better or
worse.

-cd

Jan 1 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Robin Forster | last post by:
I have two classes: aule_gl_window (parent class) and aule_button (sub class) I want to call the super class (parent) constructor code from the sub class constructor.
23
by: Fabian Müller | last post by:
Hi all, my question is as follows: If have a class X and a class Y derived from X. Constructor of X is X(param1, param2) . Constructor of Y is Y(param1, ..., param4) .
3
by: Pierre Rouleau | last post by:
The std::exception class defined in the Standard C++ <exception> header specifies that the constructors could throw any exception becuase they do not have a throw() specification. Why is that? ...
3
by: Scott Brady Drummonds | last post by:
Hi, all, I've a fairly small piece of code that is causing me problems. I'm using std::string and am building a string of several dozen characters using several of std::string's functions: a...
10
by: junw2000 | last post by:
Hi, Below is a simple code about exception. #include <iostream> using namespace std; struct E { const char* message; E(const char* arg) : message(arg) { } };
10
by: Szabolcs Horvát | last post by:
Consider the attached example program: an object of type 'A' is inserted into a 'map<int, Am;'. Why does 'm;' call the copy constructor of 'A' twice in addition to a constructor call? The...
4
by: Subra | last post by:
Hi, I am learning C++ and need export advice on the below program. I have read it that whenever a exception is genrated and control enteres the catch block it will call destructors for all the...
5
by: Vijay | last post by:
Hi All, I am not able to figure out what exactly happening in below code. what is control flow. Can anyone clear my confusion? Code: class A { public: A(){cout<<"In Constructor\n";}
6
by: asm23 | last post by:
Hi, everyone, I'm learning <<thinking c++>volume Two, and testing the code below. ///////////////////////////////////////////////////////////////////////////// //: C01:Wrapped.cpp #include...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.