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

destructor / semantics of delete this

Hi,

I have some question about the usage of delete. I have some reference
counted classes, all derived from SharedObject. It's destructor looks like
this:

~SharedObject()
{
if (--references_ == 0) {
delete this;
}
}

Now I'd like to know if
a) it's OK to use delete this (especially in the destructor)
and
b) my guess, about what happens, is correct.
In my understanding the destructor is entered and delete this is executed
(if "if" is entered of course). Delete, as far as I know, calls the
destructor of the object again, now the if-condition is false and the
storage is freed due to the first call of delete.
I may be absolutely wrong. I would not wonder. But what does really happen
and is it a good idea at all to use delete this.

regards,
alex
Jul 19 '05 #1
6 15701
"Alexander Stippler" <st**@mathematik.uni-ulm.de> wrote in message
news:3f******@news.uni-ulm.de...
| I have some question about the usage of delete. I have some reference
| counted classes, all derived from SharedObject. It's destructor looks like
| this:
|
| ~SharedObject()
| {
| if (--references_ == 0) {
| delete this;
| }
| }

This won't work. Once the destructor is executed, it is too late to
try to cancel the destruction process.
You need to use a different approach:
class SharedObject
{
public:
SharedObject() : refCnt(1) {}
void addRef() { ++refCnt; }
void release() { if(!--refCnt) delete this; }
protected:
virtual ~SharedObject()=0; // abstract class
private:
int refCnt;
};
SharedObject::~SharedObject() {}

Such a base class is usually combined with a smart pointer.
+ templates are to be considered for type safety.

Note that reference-counted classes is a well studied subject in C++.
Make sure to read advice from Scott Meyers and others on the subject.
Also, existing implementations such as boost::shared_ptr definitely
are to be considered:
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
| Now I'd like to know if
| a) it's OK to use delete this (especially in the destructor)
Yes in rare and specific cases -- but never in the destructor.

| b) my guess, about what happens, is correct.
| In my understanding the destructor is entered and delete this is executed
| (if "if" is entered of course). Delete, as far as I know, calls the
| destructor of the object again, now the if-condition is false and the
| storage is freed due to the first call of delete.
This leads to undefined behavior. Not only is it illegal to call the
destructor twice. But also, the call to 'delete' will attempt to free
memory (=> the same memory block will be freed twice, or the call
will attempt to free a stack-based address... not good at all).
I hope this helps,
Jul 19 '05 #2

"Alexander Stippler" <st**@mathematik.uni-ulm.de> wrote in message
news:3f******@news.uni-ulm.de...
Hi,

I have some question about the usage of delete. I have some reference
counted classes, all derived from SharedObject. It's destructor looks like
this:

~SharedObject()
{
if (--references_ == 0) {
delete this;
}
}

Now I'd like to know if
a) it's OK to use delete this (especially in the destructor)
and
b) my guess, about what happens, is correct.
In my understanding the destructor is entered and delete this is executed
(if "if" is entered of course). Delete, as far as I know, calls the
destructor of the object again, now the if-condition is false and the
storage is freed due to the first call of delete.
I may be absolutely wrong. I would not wonder. But what does really happen
and is it a good idea at all to use delete this.

As it's already been pointed out by Ivan it's not a good idea to use delete
this in a dtor. You will end up in a recursive call of the dtor which stops
after 2 iterations but still it's illegal to call the dtor of an object
twice. I'd recommend to read Scott Meyer's article from April 1998 in the
C++ Users Journal and there are countless others covering this topic. You
can furthermore refer to the FAQ 16.21 for a brief overview.

HTH
Chris
Jul 19 '05 #3
Chris Theis wrote:
As it's already been pointed out by Ivan it's not a good idea to use
delete this in a dtor. You will end up in a recursive call of the dtor
which stops after 2 iterations but still it's illegal to call the dtor
of an object twice.


Not only will the destructor be called twice, but the memory will be
released twice, unless the object wasn't dynamically allocated. I this
case, delete is called for an object that never came from new.
While, depending on the situation, some compilers may let you go away
with two destructor calls, the other thing almost always results in a
crash. Generally, none of those things are allowed in C++.

Jul 19 '05 #4
CT> I'd recommend to read Scott Meyer's article from April 1998 in the
CT> C++ Users Journal.

You can find it here:

http://www.cuj.com/documents/s=8066/cuj9804meyers/
Jul 19 '05 #5
> I hope this helps,

It helped a lot. Thanks
Jul 19 '05 #6

"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bh*************@news.t-online.com...
Chris Theis wrote:
As it's already been pointed out by Ivan it's not a good idea to use
delete this in a dtor. You will end up in a recursive call of the dtor
which stops after 2 iterations but still it's illegal to call the dtor
of an object twice.
Not only will the destructor be called twice, but the memory will be
released twice, unless the object wasn't dynamically allocated. I this
case, delete is called for an object that never came from new.


You're of course right on this point, which I should have mentioned for
completeness.
While, depending on the situation, some compilers may let you go away
with two destructor calls, the other thing almost always results in a
crash. Generally, none of those things are allowed in C++.


If I get you correctly you indicate that there might be situations
("...almost always...") when calling delete twice on an object will not
result in a crash. Just out of curiosity could you give me an example.

Regards
Chris
Jul 19 '05 #7

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

Similar topics

20
by: Agent Mulder | last post by:
Hi group, I have a class called container with a vector of pointers to some base class as member. Can someone help me find the right destructor for this class? Thanks, Martijn Mulder
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...
3
by: Pushkar Pradhan | last post by:
I have a function which holds a list of my data structure PARTICLE, initially the list is declared empty, but I grow it in this function. Now my question is do I have to write a destructor (since...
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...
3
by: Raider | last post by:
I have library with some class having no virtual functions and non virtual destructor. I want to add new member functions to this class by creating derived class and then use derived class...
5
by: junw2000 | last post by:
I use the code below to study delete and destructor. #include <iostream> using namespace std; struct A { virtual ~A() { cout << "~A()" << endl; }; //LINE1 void operator delete(void* p) {...
23
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....
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? ...
6
by: Fred | last post by:
Is it legal to invoke my destructor from within an instance function? For example, bool MyClass::someFunction() { SomeOtherClass:someFunction(this); // No other references to 'this' // after...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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.