473,503 Members | 1,746 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

delete this;

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
it's own memory, not a good thing in my opinion.

the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).

now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.

so, am I stupid, or was he full of shit?

Thanx
Apr 18 '06 #1
16 10306
On Tue, 18 Apr 2006 10:12:03 -0400, "Martin Vorbrodt"
<mv*******@poczta.onet.pl> wrote:
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
it's own memory, not a good thing in my opinion.

the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).

now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.

so, am I stupid, or was he full of shit?

Thanx


http://www.parashift.com/c++-faq-lit...html#faq-16.15
Apr 18 '06 #2
Martin Vorbrodt wrote:
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
it's own memory, not a good thing in my opinion.

the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).

now, i know C++ pretty darn well, but I'm not the all mighty guru... yet.

so, am I stupid, or was he full of shit?

Thanx


You're both wrong. It is a perfectly legitimate thing to do. It works,
it does execute the destructor, and does free the memory.

--
Scott McPhillips [VC++ MVP]

Apr 18 '06 #3

Martin Vorbrodt wrote:
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
it's own memory, not a good thing in my opinion.

the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).


http://www.parashift.com/c++-faq-lit...html#faq-16.15

Regards,
Sumit.

Apr 18 '06 #4
Martin Vorbrodt wrote:
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?
It depends on how the object was created. The behaivor is well-defined if
the object was created with operator new. If it's an automatic or static
objec, the behavior is undefined.
object kills itself and frees it's own memory, not a good thing in my
opinion.
Maybe, but that wasn't the question, as I see it.
the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).


Well, that's wrong. Unless you give it a null pointer (in which case it does
nothing) or a pointer that didn't come from new (in which case, the
behavior is undefined), delete always frees memory. I have no idea
what "reload the object" means. Sometimes, an explicit destructor call and
placement new are used in operator=.

Apr 18 '06 #5
hi,
hey same kind of question was asked to me too!
he asked me if we delete ' this '
in destrcutor what will happen?
i.e
class foo{
public:
//
~foo()
{
delete this;
}
};
i think this wud result in recursive calls to destructor and stack wud
overflow

Apr 18 '06 #6

Martin Vorbrodt wrote:
the guy tried to convince me that it's a common practice to "reload the
object", and that this delete would not actually free memory, only call
destructor(s).


Yeah, many times the person interviewing doesn't know shit.

Apr 18 '06 #7
Kai
Hi,

Actually, 'delete this;' is legal. The compiler doesn't mind, and would
really delete 'this'. But it's stupid under most situation. see the
following from
http://www.progsoc.uts.edu.au/lists/.../msg00010.html

Title: RE: [ProgSoc] delete self in c++
Yeah it's okay to do this .. it's most often used inside
the constructor to destroy the object if the object itself
isnt valid.
Generally speaking, I'd recommend against using "delete this" in code.
The main problem is that the object can only be created via "new". 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. If you really want to use "delete
this" in your own code, make the destructor protected, 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 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. 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.

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.

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 if a newed object
throws an exception in its constructor. 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. 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. 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!";
zero_ptr(s);
printf(s); // Shows "Hello, world!"

Anthony Langsworth
Software Developer
Computing Edge
mailto:an******@nospam.computingedge.com.au

Apr 18 '06 #8

Kai wrote:
Hi,

Actually, 'delete this;' is legal. The compiler doesn't mind, and would
really delete 'this'. But it's stupid under most situation. see the
following from
http://www.progsoc.uts.edu.au/lists/.../msg00010.html

Title: RE: [ProgSoc] delete self in c++
Yeah it's okay to do this .. it's most often used inside
the constructor to destroy the object if the object itself
isnt valid.


Generally speaking, I'd recommend against using "delete this" in code.
The main problem is that the object can only be created via "new". 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. If you really want to use "delete
this" in your own code, make the destructor protected, preventing other
classes from deleting the object and causing a compiler error if an
auto variable of this class is ever declared.


You would also want to privatize constructors and implement static
factory methods to be sure the object is always created with new.

Apr 18 '06 #9
* Noah Roberts:
* Kai:
If you really want to use "delete
this" in your own code, make the destructor protected, preventing other
classes from deleting the object and causing a compiler error if an
auto variable of this class is ever declared.


You would also want to privatize constructors and implement static
factory methods to be sure the object is always created with new.


No, that's an /alternative/ to making the destructor protected (or private).

It is IMO generally an inferior alternative.

See section 1.3.3 of my little introduction to pointers at <url:
http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf>, which
also, in section 1.3.5, discusses how to in-practice disable direct use
of new, e.g. for an object that must assume it's managed via a smart
pointer of some particular kind.
--
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?
Apr 18 '06 #10
Rolf Magnus wrote:
what "reload the object" means. Sometimes, an explicit destructor call and
placement new are used in operator=.


does this have any advantage over creating init() and destroy() member
functions?

Apr 18 '06 #11
tedu wrote:
Rolf Magnus wrote:
what "reload the object" means. Sometimes, an explicit destructor call
and placement new are used in operator=.


does this have any advantage over creating init() and destroy() member
functions?


Not sure if that could be seen as an advantage, but you can initialize
reference and const members in the constructor, but not in an init()
function. Hmm, actually, I have used that so that I can have a reference
member and still also an operator= that can change that reference.

Apr 19 '06 #12
delete this; is very useful when you have to release a object created
in a DLL.

Apr 19 '06 #13
Tom
It is legal, but I don't like it. I guess it is used when this object
need control its life by itself. In most cases, its life is controlled
by others. Or, the object is allocated in heap, but I want it to be
released automatically.

For the objects in DLL, I like to define a corresponding smart pointer
in DLL to release it (not template, it doesn't work).

Apr 20 '06 #14
Martin Vorbrodt wrote:
-snip-

In the topic line you wrote that I should delete your message. I can't......

My newsreader complaints about: "This message does not appear to be from
you. You may only cancel your own posts, not those made by others."
LOL :-)
Best regards / Med venlig hilsen
Martin Jørgensen

--
---------------------------------------------------------------------------
Home of Martin Jørgensen - http://www.martinjoergensen.dk
Apr 20 '06 #15

Tom wrote:
It is legal, but I don't like it. I guess it is used when this object
need control its life by itself. In most cases, its life is controlled
by others. Or, the object is allocated in heap, but I want it to be
released automatically.

For the objects in DLL, I like to define a corresponding smart pointer
in DLL to release it (not template, it doesn't work).


You are right.But it`s used widely in LIB.

Apr 20 '06 #16
You are right.But it`s used widely.

Apr 20 '06 #17

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

Similar topics

2
6971
by: foo | last post by:
I'm creating a debug class called debug_mem_allocation for the purpose of finding memory leaks. I used macro's to replace the new and delete operators. My problem is with trying to replace the...
15
2361
by: Roy Smith | last post by:
I understand that "delete xp" deletes a scalar object and "delete xp" deletes an array of objects, but what I don't understand is why you need to tell the compiler which you're doing. When you...
13
5867
by: Amy | last post by:
Hello, We are developing C++ appplications for PDAs where memory is limited, so we want to do memory management by ourselves --- pre-allocated a big chunk and overwrite new and delete to call...
5
4850
by: mandatory | last post by:
hi, i have a pointer to a class, which is dynamically allocated with new. myClass *mC = new myClass(); What if i at a later point in my code i have this: void *pointer;
8
25027
by: John Baker | last post by:
Hi: Access 2000 W98! I have a table with numerous records in it, and am attempting to delete certain records that have been selected from it. These are selected based on the ID number in a...
3
4633
by: silver360 | last post by:
Hello, I'm trying to create a basic Heap manager and i have some question about new/delete overloading. The following code give me this output : >> $./heap >> registered : 0x804d098 >>...
10
1861
by: junw2000 | last post by:
Hi, Below is a small code about memory allocation and deallocation. #include <cstdlib> #include <iostream> using namespace std; class X { public: void* operator new(size_t sz) throw (const...
5
5505
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) {...
9
8145
by: rohits123 | last post by:
I have an overload delete operator as below ////////////////////////////////// void operator delete(void* mem,int head_type) { mmHead local_Head = CPRMemory::GetMemoryHead(head_type);...
29
2222
by: =?Utf-8?B?R2Vvcmdl?= | last post by:
Hello everyone, I remembered delete is implemented through operator overloading, but I am not quite clear. Could anyone recommend some links about how delete is implemented so that I can...
0
7199
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
7074
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...
0
7322
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...
1
6982
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...
0
7451
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
4667
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...
0
3150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1501
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 ...
1
731
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.