473,666 Members | 2,096 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete this, Arrrrrgh!!


In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?

JB
Nov 22 '05 #1
10 1462
"n2xssvv g02gfr12930" <n2************ *****@ntlworld. com> wrote in message
news:Px******** ***********@new sfe4-gui.ntli.net...

In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?

JB


Perhaps for some factory object. Or an object that only intended to be a
temporary or something.

Actually, if an object is on some list of pointers and it determines to
delete itself from the list, perhaps it could remove itself from the list
then delete itself.

I'm not sure if I'd ever do that though because it would throw off the list
iterators.

Hard to say. I'm sure somewhere someone has come up with a good reason to
use it, whether we agree with them or not.
Nov 22 '05 #2
* n2xssvv g02gfr12930:

In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?


It's common and practically necessary for e.g. objects that represent
windows in a graphical user interface. A different design choice is to
allow such objects to have a nullstate. That leads to an awful lot of
nullstate checking and in general a non-OO system architecture.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 22 '05 #3
* /Gogineni/:
http://www.progsoc.uts.edu.au/lists/.../msg00010.html
Referring to a lot of dis-information by
* Anthony Langsworth, Mon, 2 Oct 2000:
Generally speaking, I'd recommend against using "delete this" in code. The
main problem is that the object can only be created via "new".
Which is not a problem.

If the object is declared "auto" (i.e. not a pointer or reference) and "delete
this" is called it will fail because "this" was not allocated with new and the
program will crash.
Which is not true: it's Undefined Behavior and there is no crash
guarantee.

If you really want to use "delete this" in your own code, make the destructor
protected,
Generally good advice.

preventing other classes from deleting the object and causing a compiler error if
an auto variable of this class is ever declared.

If you want to use in it a constructor, I'd recommend against it for the above reason
Which is meaningless or just false.

and also because the calling function has no way of knowing whether the object
encountered an error - calling one of the object's functions will result in a crash.
Which is false.

The object fails to instantiate itself will have to modify some form of global
variable such as errno, SetLastError(), IErrorInfo, etc, which, although acceptable,
is hardly ideal.
Which is an argument based on a false premise.

A much better way to report an error in an object's constructor is to use a static
"factory" function to encapsulate the construct. E.g.
static Dog* Dog::CreateDog( int legs) which can return a NULL pointer on an error.
Which is UnGood advice; generally an exception is preferable.

Alternatively, the constructor could throw an exception. Don't worry about memory
leaks, ANSI-compliant compilers should automatically deallocate the object with
calling the constructor [presumably he means: destructor] if a newed object throws
an exception in its constructor.
Which is false. Memory is reclaimed, the destructor isn't (and should
not be) called.

Check your compiler doco for this. The only situation I've seen "delete this" where I consider it an acceptable use
is the the thread or window classes from MFC.
MFC is hardly an example of good OO design; it's often used as a
counter-example.

The intention with these classes is to instantiate them, remove all references to them
and let the objects manages their own lifespans.
Also a good idea to check for null after any member function
that could cause the object to be destroyed.

I haven't got ARM (or a similar tome) handly but I suspect that modifying "this" in a
member funcion is illegal.
It is.

Either way, changing "this" in a member function will not affect the value of the
pointer the function was called through. E.g. void zero_ptr(char* s)
{
// This line only changes the local version of s.
s = NULL;
} ... char *s = "Hello, world!";
Using the deprecated conversion to char* (instead of char const*) is
abolutely not an example to follow.

zero_ptr(s);
printf(s); // Shows "Hello, world!"

Anthony Langsworth
Software Developer
Computing Edge


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 22 '05 #5
Alf P. Steinbach wrote:
* n2xssvv g02gfr12930:
In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?

It's common and practically necessary for e.g. objects that represent
windows in a graphical user interface. A different design choice is to
allow such objects to have a nullstate. That leads to an awful lot of
nullstate checking and in general a non-OO system architecture.

I'm still not happy destroying an object this way. Why not use a
static function passing the pointer and waiting for a member flag to
signal that the class can be destroyed safely then exiting without ever
returning? Then what about the implications for descendant classes? The
knots that could be tied by misuse due to misunderstandin g or sheer
incompetence don't bear thinking about.

JB
Nov 23 '05 #6
* n2xssvv g02gfr12930:
Alf P. Steinbach wrote:
* n2xssvv g02gfr12930:
In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?

It's common and practically necessary for e.g. objects that represent
windows in a graphical user interface. A different design choice is to
allow such objects to have a nullstate. That leads to an awful lot of
nullstate checking and in general a non-OO system architecture.

I'm still not happy destroying an object this way. Why not use a
static function passing the pointer and waiting for a member flag to
signal that the class can be destroyed safely then exiting without ever
returning?


Then you have one thread or at least fiber per object. We can disregard
that standard C++ doesn't support threads, because they're part of
practical C++ usage. But you really don't want one thread per object.

Then what about the implications for descendant classes?
The main implication is that derived classes ideally should ensure
dynamic allocation, e.g. by each descendant class declaring a protected
destructor, but often one just relies on the client code programmer's
good sense -- and of course that incorrect usage will be caught by
even the most cursory testing, such as trying to run the program.

The
knots that could be tied by misuse due to misunderstandin g or sheer
incompetence don't bear thinking about.


That's a general problem in software development, yes, but isn't more of
a problem here than elsewhere, as far as I can see.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 23 '05 #7
On 2005-11-22 02:12:47 -0500, n2xssvv g02gfr12930
<n2************ *****@ntlworld. com> said:

In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?


Imagine a reference counted class that automatically deletes itself
when all of it's clients drop their references:

class Refcounted
{
int reference_count ;
protected:
virtual ~Refcounted() { assert(referenc e_count <= 0); }
public:
Refcounted() : reference_count (0) {}
Refcounted(Refc ounted const &) : reference_count (0) {}

void add_reference() { ++reference_cou nt; }
void drop_reference( ) { if(--reference_count <= 0) delete this; }
};
--
Clark S. Cox, III
cl*******@gmail .com

Nov 23 '05 #8

Clark S. Cox III wrote:
On 2005-11-22 02:12:47 -0500, n2xssvv g02gfr12930
<n2************ *****@ntlworld. com> said:

In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?
Imagine a reference counted class that automatically deletes itself
when all of it's clients drop their references:

class Refcounted
{
int reference_count ;
protected:
virtual ~Refcounted() { assert(referenc e_count <= 0); }


"assert ( reference_count < 0 )" or "reference_coun t (1)"
public:
Refcounted() : reference_count (0) {}
Refcounted(Refc ounted const &) : reference_count (0) {}

void add_reference() { ++reference_cou nt; }
void drop_reference( ) { if(--reference_count <= 0) delete this; }
same here.
};
--
Clark S. Cox, III
cl*******@gmail .com


Nov 23 '05 #9
On Tue, 22 Nov 2005 04:59:04 -0500, Clark S. Cox III
<cl*******@gmai l.com> wrote:
On 2005-11-22 02:12:47 -0500, n2xssvv g02gfr12930
<n2*********** ******@ntlworld .com> said:

In a job interview I was asked about the statement below:

delete this;

Naturally I was horrified, yet they claimed they had used it.
Personally I'm pretty damn sure I could never justify this. So
is this a case of Lord Bryon, "Mad, bad, and dangerous to know",
or do you think you could ever justify using it?


Imagine a reference counted class that automatically deletes itself
when all of it's clients drop their references:

class Refcounted
{
int reference_count ;
protected:
virtual ~Refcounted() { assert(referenc e_count <= 0); }
public:
Refcounted() : reference_count (0) {}
Refcounted(Refc ounted const &) : reference_count (0) {}

void add_reference() { ++reference_cou nt; }
void drop_reference( ) { if(--reference_count <= 0) delete this; }
};


Is it safe to "delete this;" from any method, as long as you don't
access any more class members? I imagine it just deletes itself, gets
to the end of the method and returns safely, right?
Nov 23 '05 #10

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

Similar topics

6
15723
by: Alexander Stippler | last post by:
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;
10
2142
by: solosnake | last post by:
Whilst browsing Flipcode I noticed this code: class CConsole: public I_TextOutput { public: ... void Release() { delete this; } ... };
5
1643
by: Yongming Wang | last post by:
FuncA is called to delete itself with B's help. In vc 7.0, case 1 seems invalid, but case 2 is valid. Could anyone explain for me? class A { public: void FuncA() { B b(this);
16
10328
by: Martin Vorbrodt | last post by:
some butthole asked me an interview question: can you delete "this" pointer in a member function of a class, like this: class C { public: void foo() { delete this; } }; my answer was... undefined behavior, maybe? object kills itself and frees
31
8466
by: Anamika | last post by:
Hello friends.... can anyone tell me what will happen when we do..."delete this"...
4
1134
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, Just interested to learn how C++ implements delete this statement internally. From logical point of view, I can not imagine how to implement a component which destroy itself. What makes me confused is the component is relying on itself even in the process of destroy, how could it destroys itself from itself?
1
1672
by: MorgyTheMole | last post by:
I have a base class: class A { protected: static void* operator new (size_t size); void operator delete (void *p); public: void Delete(); }
5
588
by: WaterWalk | last post by:
Hello. The question about "deleting this inside the class's member function" is discussed many times in this group and in the "C++ FAQs". But I still have two more questions. 1. Take the following class as an example: class Test { public: static void print_message(char *s) { printf("%s\n", s); } void delete_me()
0
8356
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
8871
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...
1
8552
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
7387
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5666
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();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2773
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
2011
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.