473,803 Members | 3,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why not destructor?

I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?

--
Regards
Sharon G.
Nov 16 '05 #1
11 2833
Sharon <Sh****@discuss ions.microsoft. com> wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


I believe you mean destructor, not constructor.

Finalizers (which are what you actually get) aren't called
deterministical ly - they're called when the GC gets round to it. This
could be much later than you really want, and indeed it may never
happen at all. That's a really bad situation to be in if you need to
free up resources so that something else can use them.

Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #2
"Sharon" <Sh****@discuss ions.microsoft. com> wrote in message
news:20******** *************** ***********@mic rosoft.com...
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


Constructor is fine (your message). The problem with destructors (your
subject) is that in .NET you don't know when they will execute, since
objects aren't destroyed when they go out of scope, but when the garbage
collector cleans then up. The Dispose pattern gives you guaranteed execution
when Dispose is called.

Tim
..NET pros and cons
http://www.itwriting.com/phorum/list.php?f=6
Nov 16 '05 #3
There are various problems with the C# 'destructor'.

First, you never know when or if it will be called. So it's not like a C++
destructor, where it gets called the moment the object goes out of scope or
is deleted. It won't be called until a garbage collect occurs. If your
system is not busy right now it could literally be hours before the
destructor runs, even though the object is out of use.

When your application exits, .NET tries to run all finalizers (C#
destructors are really finalizers in disguise), but if it takes more than a
few seconds, it just gives up. So you can never be sure the destructor will
run.

Also, you can't use other finalizable objects from within your destructor.
(I.e. other objects that have destructors.) This is because .NET makes no
guarantees about the order in which it runs finalizers. So it's quite
possible that any objects you were using have already been finalized by the
time your destructor runs. Calling methods on an object whose destructor
has already been run is never a good idea. And since you can't be sure
which ones have been finalized (or indeed which of the objects you are using
even have a finalizer) it's not safe to use objects.

So all of that means that destructors aren't actually a great deal of use.
The main reason for implementing a finalizer is because your object wraps
some kind of raw handle (e.g. a raw Win32 handle, or maybe a handle obtained
through Interop from some unmanaged library) and you need to ensure that it
gets freed. But this is just a safety net, and not a terribly reliable one,
given the limitations mentioned above.
Worse, finalizers cause performance issues. The system has to work harder
to track finalizable objects. Try writing a loop to see how fast you can
create objects without destructors and how fast you can create objects with
destructors - something like this:

int cout = 0;
while (true)
{
new MyClass();
count += 1;
if (count % 10000000 == 0) Console.WriteLi ne(count);
}

If MyClass does not have a destructor, it creates about 20 million objects a
second on my system. If it does have a destructor, it only manages about 2
million!

Also, finalizers cause objects to hang around in memory very much longer
than they otherwise would, which increases the working set of the process.

So they are best avoided.
--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/

"Sharon" wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?

Nov 16 '05 #4
Jon Skeet wrote:
Finalizers (which are what you actually get) aren't called
deterministica lly - they're called when the GC gets round to it.
This could be much later than you really want,
and indeed it may never happen at all. In what scenarios do the finalizer get omitted?
Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs. I always define a destructor for my classes.
Is that bad?
If i would not do that, then System.Object:: Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object:: Finalize(or higher
base class with Finalize overriden) was called.
--
Regards,
Dennis JD Myrén
Oslo Kodebureau
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com... Sharon <Sh****@discuss ions.microsoft. com> wrote:
I have heard that if I add a constructor it is not good, it complicates
things and that it is better to use the Dispose.
Can anybody explain this for me?


I believe you mean destructor, not constructor.

Finalizers (which are what you actually get) aren't called
deterministical ly - they're called when the GC gets round to it. This
could be much later than you really want, and indeed it may never
happen at all. That's a really bad situation to be in if you need to
free up resources so that something else can use them.

Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 16 '05 #5
Great post Ian,

I would just want to add that if you really need a destructor you should
make a rule of implementing the IDisposible interface as well.

While it doesn't take care of the perf issue Ian mentions, it gives the
user of your class a chance to release the external resources before
they remove the root reference to the object. Additionally we could turn
the finalizer off for our object when we know that the dispose method
has been called.

In thoose scenarios I usally conform to the following:

private void Dispose(bool disposing)
{
// release stuff

if ( disposing )
GC.SupressFinil ize(this);
}

public void Dispose()
{
this.Dispose(tr ue);
}

~MyClass()
{
this.Dispose(fa lse);
}

--
Patrik Löwendahl [C# MVP]
cshrp.net - 'Elegant code by witty programmers'
cornerstone.se 'IT Training for professionals'

Ian Griffiths [C# MVP] wrote:
There are various problems with the C# 'destructor'.

First, you never know when or if it will be called. So it's not like a C++
destructor, where it gets called the moment the object goes out of scope or
is deleted. It won't be called until a garbage collect occurs. If your
system is not busy right now it could literally be hours before the
destructor runs, even though the object is out of use.

When your application exits, .NET tries to run all finalizers (C#
destructors are really finalizers in disguise), but if it takes more than a
few seconds, it just gives up. So you can never be sure the destructor will
run.

Also, you can't use other finalizable objects from within your destructor.
(I.e. other objects that have destructors.) This is because .NET makes no
guarantees about the order in which it runs finalizers. So it's quite
possible that any objects you were using have already been finalized by the
time your destructor runs. Calling methods on an object whose destructor
has already been run is never a good idea. And since you can't be sure
which ones have been finalized (or indeed which of the objects you are using
even have a finalizer) it's not safe to use objects.

So all of that means that destructors aren't actually a great deal of use.
The main reason for implementing a finalizer is because your object wraps
some kind of raw handle (e.g. a raw Win32 handle, or maybe a handle obtained
through Interop from some unmanaged library) and you need to ensure that it
gets freed. But this is just a safety net, and not a terribly reliable one,
given the limitations mentioned above.
Worse, finalizers cause performance issues. The system has to work harder
to track finalizable objects. Try writing a loop to see how fast you can
create objects without destructors and how fast you can create objects with
destructors - something like this:

int cout = 0;
while (true)
{
new MyClass();
count += 1;
if (count % 10000000 == 0) Console.WriteLi ne(count);
}

If MyClass does not have a destructor, it creates about 20 million objects a
second on my system. If it does have a destructor, it only manages about 2
million!

Also, finalizers cause objects to hang around in memory very much longer
than they otherwise would, which increases the working set of the process.

So they are best avoided.

Nov 16 '05 #6
If you put GC.SuppressFina lize in your Dispose, and Dispose is called, it does stop the performance issues with finallizers as the GC will not put the object on the finalization queue (and so promote it to Gen1 in the process)

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

Great post Ian,

I would just want to add that if you really need a destructor you should
make a rule of implementing the IDisposible interface as well.

While it doesn't take care of the perf issue Ian mentions, it gives the
user of your class a chance to release the external resources before
they remove the root reference to the object. Additionally we could turn
the finalizer off for our object when we know that the dispose method
has been called.

Nov 16 '05 #7
The GC only puts the object on the finalization queue if it's class *overrides* Finalize, or its base class other than System.Object has overridden Finalize. So if you omit it no finalization takes place. So *never* override finalize (implement a destructor) unless you really need it - in other words only if you've got hold of an unmanaged resource via interop that needs freeing should you provide a destructor.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk

I always define a destructor for my classes.
Is that bad?
If i would not do that, then System.Object:: Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object:: Finalize(or higher
base class with Finalize overriden) was called.

Nov 16 '05 #8
"Dennis Myrén" wrote:
I always define a destructor for my classes.
Is that bad?
Yes. It means your objects will always survive on the managed heap for far
longer than is necessary. And by extension, so will any objects that your
objects refer to.

If i would not do that, then System.Object:: Finalize
would provide the destructor and it would run anyway, would it not?
Actually no. If you don't override the Finalize method, the CLR never calls
it. It knows that System.Object doesn't do anything in its Finalize method,
so it doesn't call it. The only reason Object has a a Finalize method is so
that you can override it.

I thought the destructor was an overridden method from
System.Object, and if it was not overridden, then the
System.Object:: Finalize(or higher base class with
Finalize overriden) was called.


Yes it is an overridden method, but no, if it's not overridden then the CLR
knows it doesn't have to call it.

--
Ian Griffiths - http://www.interact-sw.co.uk/iangblog/
DevelopMentor - http://www.develop.com/
Nov 16 '05 #9
Dennis Myrén <de****@oslokb. no> wrote:
Jon Skeet wrote:
Finalizers (which are what you actually get) aren't called
deterministica lly - they're called when the GC gets round to it.
This could be much later than you really want,
and indeed it may never happen at all. In what scenarios do the finalizer get omitted?


If finalization of all objects is taking too long when a process ends.
Finalizers also take longer to free up, as the GC has to notice that
nothing is referencing the object, run the finalizer, and then actually
reclaim the memory the following time it runs.

I always define a destructor for my classes.
Is that bad?


Yes.
If i would not do that, then System.Object:: Finalize
would provide the destructor and it would run anyway, would it not?
I thought the destructor was an overridden method from System.Object,
and if it was not overridden, then the System.Object:: Finalize(or higher
base class with Finalize overriden) was called.


object.Finalize doesn't do anything, and the CLR knows this - so it
only puts things which override Finalize onto the finalization queue.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #10

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

Similar topics

52
27043
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 will call it's destructor when it is made a target of a delete".
11
10526
by: Stub | last post by:
Please answer my questions below - thanks! 1. Why "Derived constructor" is called but "Derived destructor" not in Case 1 since object B is new'ed from Derived class? 2. Why "Derived destructor" is called in Case 2 since only ~base() becomes "virtual" and ~Derived() is still non-virtual? 3. Does Case 3 show that we don't need any virtual destructor to make ~Derived() called? 4. Is "virtual destructor" needed only for Case 2?
26
3989
by: pmizzi | last post by:
When i compile my program with the -ansi -Wall -pedantic flags, i get this warning: `class vechile' has virtual functions but non-virtual destructor, and the same with my sub-classes. But when i add a virtual destructor like this : " virtual ~vechile". I get this error: Undefined first referenced symbol in file vtable for vechile /var/tmp//ccC9yD6Z.o
11
5314
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 4-month old C#/MC++ .NET project project. I'd like to thank in advance anyone who takes the time to read and/or respond to this message. At a couple points, it may seem like a rant against C# / .NET, but we are pretty firmly stuck with this approach...
35
3330
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 member. However, I set a breakpoint at the destructor of this instance's class and it was never called!!! I can see how it might not get called at a deterministic time. But NEVER? So, I guess I need to know the rules about destructors. I would...
14
3218
by: gurry | last post by:
Suppose there's a class A. There's another class called B which looks like this: class B { private: A a; public : B() { a.~A() } }
11
1993
by: AB | last post by:
Hi All, I've got an array of objects, during the execution of the program I'd like to assign a particular object to a certain element in the object array. The sample code's like this... class ClassA { public: ClassA()
23
2612
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624. I read the description, decided that it's exactly what I want, and ignored the warning. Now I'm trying to inherit using a template. Instead of "destructor could not be generated because a base class destructor is inaccessible", I now have an...
8
2058
by: gw7rib | last post by:
I've been bitten twice now by the same bug, and so I thought I would draw it to people's attention to try to save others the problems I've had. The bug arises when you copy code from a destructor to use elsewhere. For example, suppose you have a class Note. This class stores some text, as a linked list of lines of text. The destructor runs as follows: Note::~Note() {
7
2011
by: sam | last post by:
Hi, See when i reading a sourcecode of a program, I read that the constructor is ordinary and after that the programmer has written virtual destructor for that constructor . Why we use the virtual destructor whats the use of it? the code is like this: Network(int input,int output); Network(&Network); virtual ~Network();
0
9703
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9564
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10548
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10316
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10295
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6842
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4275
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3798
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.