473,386 Members | 1,720 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,386 software developers and data experts.

C++ vc C#. Destructor of not created class get called.

Hello All.

I've got some unexpected (to me) behavior. In C++, destructor of the class
that wasn't created is not called,
in C# some how I've got destructor call for class that wasn't initialized
properly (by constructor). Please look examples.

Is that a normal ? .. or garbage collector take care of all ?
Am I doing something wrong ?

P.S. I'm new in C#.
C++ output :
------------
C1::C1
C2::C2
C1::~C1
Exception!
Press any key to continue

C# output :
-----------
C1::C1
C2::C2
Exception!
C3::~C3
C2::~C2
C1::~C1
Press any key to continue

C++ code :
----------
class C1
{
public:
C1::C1()
{
puts("C1::C1");
}
virtual C1::~C1()
{
puts("C1::~C1");
}
};

class C2 : public C1
{
public :
C2::C2()
{
puts("C2::C2");
throw "1";
}
virtual C2::~C2()
{
puts("C2::~C2");
}
};

class C3 : public C2
{
public :
C3::C3()
{
puts("C3::C3");
}
virtual C3::~C3()
{
puts("C3::~C3");
}
};

int main(int argc, char* argv[])
{
try
{
C3 c3;
}
catch(...)
{
puts("Exception!");
}

return 0;
}

C# code :
---------
class C1
{
public C1()
{
Console.WriteLine("C1::C1");
}
~C1()
{
Console.WriteLine("C1::~C1");
}
};
class C2 : C1
{
public C2()
{
Console.WriteLine("C2::C2");
throw new Exception("1");
}
~C2()
{
Console.WriteLine("C2::~C2");
}
};
class C3 : C2
{
public C3()
{
Console.WriteLine("C3::C3");
}
~C3()
{
Console.WriteLine("C3::~C3");
}
};

class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
C3 c3 = new C3();
}
catch(Exception)
{
Console.WriteLine("Exception!");
}
}
}
Nov 16 '05 #1
5 1304

"pronto" <pr****@hotmail.com> wrote in message
news:OJ**************@TK2MSFTNGP09.phx.gbl...
Hello All.

I've got some unexpected (to me) behavior. In C++, destructor of the class
that wasn't created is not called,
in C# some how I've got destructor call for class that wasn't initialized
properly (by constructor). Please look examples.

Is that a normal ? .. or garbage collector take care of all ?
Am I doing something wrong ?
It can happen. At the moment you create an object, it exists. The
constructor does initialization, but if it throws an exception, you end up
with a partially constructed type which the GC will eventually clean up.
Finalization is also handled by the GC and will always be called for a given
instance, so it *must* be able to deal with partially constructed instances.

In most cases there is no point in using a finalizer, the GC will always
clean up managed memory. You need finalization when you are wrapping
unmanaged resources like file handles. Finalization is something you should
strive to avoid, it can be very expensive and not totally reliable(there are
a small set of circumstances where finalizers may not be run, though they
are rather rare in practice and can be pretty much eliminated with .NET 2.0,
once its released). Look up the IDisposable pattern(its not quite as easy as
RAII, but with the using keyword it works well), joining IDisoposable with
GC.SurpressFinalize can help performance substantially.

Also, if you are interested in why finalization is expensive and a bit of
how it works and feel like reading alot, check out
http://blogs.msdn.com/cbrumme/archiv.../20/77460.aspx (second time
I've linked to that today, LOL).

P.S. I'm new in C#.
C++ output :
------------
C1::C1
C2::C2
C1::~C1
Exception!
Press any key to continue

C# output :
-----------
C1::C1
C2::C2
Exception!
C3::~C3
C2::~C2
C1::~C1
Press any key to continue

C++ code :
----------
class C1
{
public:
C1::C1()
{
puts("C1::C1");
}
virtual C1::~C1()
{
puts("C1::~C1");
}
};

class C2 : public C1
{
public :
C2::C2()
{
puts("C2::C2");
throw "1";
}
virtual C2::~C2()
{
puts("C2::~C2");
}
};

class C3 : public C2
{
public :
C3::C3()
{
puts("C3::C3");
}
virtual C3::~C3()
{
puts("C3::~C3");
}
};

int main(int argc, char* argv[])
{
try
{
C3 c3;
}
catch(...)
{
puts("Exception!");
}

return 0;
}

C# code :
---------
class C1
{
public C1()
{
Console.WriteLine("C1::C1");
}
~C1()
{
Console.WriteLine("C1::~C1");
}
};
class C2 : C1
{
public C2()
{
Console.WriteLine("C2::C2");
throw new Exception("1");
}
~C2()
{
Console.WriteLine("C2::~C2");
}
};
class C3 : C2
{
public C3()
{
Console.WriteLine("C3::C3");
}
~C3()
{
Console.WriteLine("C3::~C3");
}
};

class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
C3 c3 = new C3();
}
catch(Exception)
{
Console.WriteLine("Exception!");
}
}
}

Nov 16 '05 #2

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:uV**************@TK2MSFTNGP09.phx.gbl...

"pronto" <pr****@hotmail.com> wrote in message
news:OJ**************@TK2MSFTNGP09.phx.gbl...
Hello All.

I've got some unexpected (to me) behavior. In C++, destructor of the class that wasn't created is not called,
in C# some how I've got destructor call for class that wasn't initialized properly (by constructor). Please look examples.

Is that a normal ? .. or garbage collector take care of all ?
Am I doing something wrong ?


It can happen. At the moment you create an object, it exists. The
constructor does initialization, but if it throws an exception, you end up
with a partially constructed type which the GC will eventually clean up.


Assuming there are no references to it. This is ordinarily true, but there
are exceptions (all the ones I know of being pathological.) See
http://groups.google.com/groups?hl=e...168.3.44#link1
for some examples.
Nov 16 '05 #3

"Mike Schilling" <ms*************@hotmail.com> wrote in message
news:%2****************@TK2MSFTNGP10.phx.gbl...

"Daniel O'Connell [C# MVP]" <onyxkirx@--NOSPAM--comcast.net> wrote in
message news:uV**************@TK2MSFTNGP09.phx.gbl...

"pronto" <pr****@hotmail.com> wrote in message
news:OJ**************@TK2MSFTNGP09.phx.gbl...
> Hello All.
>
> I've got some unexpected (to me) behavior. In C++, destructor of the class > that wasn't created is not called,
> in C# some how I've got destructor call for class that wasn't initialized > properly (by constructor). Please look examples.
>
> Is that a normal ? .. or garbage collector take care of all ?
> Am I doing something wrong ?
It can happen. At the moment you create an object, it exists. The
constructor does initialization, but if it throws an exception, you end
up
with a partially constructed type which the GC will eventually clean up.


Assuming there are no references to it. This is ordinarily true, but
there
are exceptions (all the ones I know of being pathological.) See
http://groups.google.com/groups?hl=e...168.3.44#link1
for some examples.


It is quite possible for a reference to become available without being
constructed. I didn't mean to imply that it will never be referenced
anywhere, just that it will be GC'd and finalized just like every other
object, even though it is only partially constructed. Writing code that
actually allows a reference to a partially constructed type generally does
have to be intentional, however. I know of no way to do it without the
object itself choosing to reference itself somewhre(this is a reason why
registering an object in a static collection from a constructor is a *bad*
idea unless its sealed, etc).

Its also quite possible, as the last message in that thread shows, for the
finalizer of a given object to resurrect itself, its just not common.

Nov 16 '05 #4
> It is quite possible for a reference to become available without being
constructed. I didn't mean to imply that it will never be referenced
anywhere, just that it will be GC'd and finalized just like every other
object, even though it is only partially constructed. Writing code that
actually allows a reference to a partially constructed type generally does
have to be intentional, however. I know of no way to do it without the
object itself choosing to reference itself somewhre(this is a reason why
registering an object in a static collection from a constructor is a *bad*
idea unless its sealed, etc).

Maybe it is a bit OT here, but is there a way to invoke undefined behaviour
when calling a virtual method from within the ctor of an object or calling a
virtual method on a incomplete constucted object?
I tried all stuff but there was never the wrong method called or any
Exception thrown.

--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk
Nov 16 '05 #5

"cody" <pl*************************@gmx.de> wrote in message
news:OY**************@tk2msftngp13.phx.gbl...
It is quite possible for a reference to become available without being
constructed. I didn't mean to imply that it will never be referenced
anywhere, just that it will be GC'd and finalized just like every other
object, even though it is only partially constructed. Writing code that
actually allows a reference to a partially constructed type generally
does
have to be intentional, however. I know of no way to do it without the
object itself choosing to reference itself somewhre(this is a reason why
registering an object in a static collection from a constructor is a
*bad*
idea unless its sealed, etc).

Maybe it is a bit OT here, but is there a way to invoke undefined
behaviour
when calling a virtual method from within the ctor of an object or calling
a
virtual method on a incomplete constucted object?
I tried all stuff but there was never the wrong method called or any
Exception thrown.


There isn't any undefined behaviour that I know of in the *runtime*, the
risk you run when calling a virtual method from a constructor is that the
constructor for the type that overrides that method may not have been called
and it may not have been initalized.
--
cody

[Freeware, Games and Humor]
www.deutronium.de.vu || www.deutronium.tk

Nov 16 '05 #6

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

Similar topics

52
by: Newsnet Customer | last post by:
Hi, Statement 1: "A dynamically created local object will call it's destructor method when it goes out of scope when a procedure returms" Agree. Statement 2: "A dynamically created object...
9
by: sahukar praveen | last post by:
Hello, This is the program that I am trying. The program executes but does not give me a desired output. ********************************************** #include <iostream.h> #include...
7
by: Douglas Peterson | last post by:
Take a look at this code, it looks funny as its written to be as short as possible: -- code -- struct Base { ~Base() { *((char*)0) = 0; } }; struct Derived : public Base
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: Tony Johansson | last post by:
Hello experts! I have this piece of code. No user defined copy constructor exist. AccountForStudent create(long number) { AccountForStudent local(number, 0.0); return local; } int main() {
6
by: Squeamz | last post by:
Hello, Say I create a class ("Child") that inherits from another class ("Parent"). Parent's destructor is not virtual. Is there a way I can prevent Parent's destructor from being called when a...
11
by: Ken Durden | last post by:
I am in search of a comprehensive methodology of using these two object cleanup approaches to get rid of a number of bugs, unpleasantries, and cleanup-ordering issues we currently have in our...
6
by: mupp | last post by:
I am wondering if someone could please explain the behaviour observed in the following example: class Contained { ~Contained () { } }
35
by: Peter Oliphant | last post by:
I'm programming in VS C++.NET 2005 using cli:/pure syntax. In my code I have a class derived from Form that creates an instance of one of my custom classes via gcnew and stores the pointer in a...
12
by: Rahul | last post by:
Hi Everyone, I have the following code and i'm able to invoke the destructor explicitly but not the constructor. and i get a compile time error when i invoke the constructor, why is this so? ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.