Hi All,

Can we delete this pointer from a member function.

I have written three programs to try this. The first two crashes at run time while the third doesn't. Can somebody explain me this?????

1) This crashes at run time.

#include <iostream>
using namespace std;
class Base
{
public:
 void temp(void)
 {
  delete this;
 }
};

int main(void)
{
 Base x;
 x.temp();
 return 0;
}

2. This also...

#include <iostream>
using namespace std;
class Base
{
public:
 void temp(void)
 {
  delete this;
 }
};

int main(void)
{
 Base x;
 Base *p = &x;
 p->temp();
 return 0;
}

3) This doesn't

#include <iostream>
using namespace std;
class Base
{
public:
 void temp(void)
 {
  delete this;
 }
};

int main(void)
{
 Base *p = new Base;
 p->temp();
 return 0;
}

Recommended Answers

All 8 Replies

That link doesn't provide the reason why the program crashes if the object is on stack.

That link doesn't provide the reason why the program crashes if the object is on stack.

Reason #1 doesn't hit the nail on the head?

  1. You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).

[edit]

1) This crashes at run time.

Base x; // local object on the stack
 x.temp();

2. This also...

Base x; // local object on the stack
 Base *p = &x;
 p->temp();

3) This doesn't

Base *p = new Base; // object allocated with plain ordinary new
 p->temp();

[edit=2]Oh, wait -- why? I dunno. Because you're not supposed to. Which is to say that most likely somewhere it officially states that it is undefined behavior to do so, and the people who write compilers likely had a legitimate complaint; the upshot being don't do this.

So .... R you trying to say that its a standard ...
If at all its a standard, there should be some reason as of why the standard is not allowing it

So .... R you trying to say that its a standard ...
If at all its a standard, there should be some reason as of why the standard is not allowing it

You can buy a copy and search through the 700+ pages if you like. Or you can trust the people (not me, by the way) who have bought a copy and thought over the relevant parts and produced implementations and influenced the standard itself. Sometimes the reasons go by the term "Rationale"

[edit]Not fruitful. But

D&E - Bjarne Stroustrup: The Design and Evolution of C++. Addison Wesley. 1994. A book describing why C++ looks the way it does - the closest to a design rationale that we have for C++.

http://www.research.att.com/~bs/dne.html

Good explanation.
Thanks Dave

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.