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;
}

Dani AI

Generated

Short answer: calling delete this is legal only when the object really came from new; otherwise the program has undefined behavior, which explains why your first two examples crash while the third does not. The language rule is that the operand of a delete must be a null pointer or a pointer to an object created by a matching new expression. (en.cppreference.com)

Why that matters: delete does two things — it runs the destructor, then it calls the deallocation function (operator delete) which expects a heap block returned by new. If you pass the address of a stack object, the deallocation step is operating on memory it never allocated; that can corrupt heap metadata or otherwise crash immediately, but because the behavior is undefined it can also appear to “work” on some runs or platforms. (en.cppreference.com)

When delete this is reasonable: use it only in tightly controlled designs where you can guarantee heap allocation (not new[], not placement new) and that no code touches the object after the delete. If deletion might happen through a base-class pointer, the base needs a virtual destructor so the most-derived destructor runs. delete this is commonly seen in intrusive ref‑counted objects and similar patterns, but it’s a fragile idiom and must be documented and enforced. (isocpp.org)

A safer pattern is to avoid self-deletion and express ownership explicitly (smart pointers or a factory + private destructor). Example heap-only factory that makes delete this harder to misuse:

class Foo {
public:
  static Foo* create() { return new Foo; }
  void destroy() { delete this; }   // safe only if every Foo comes from create()
private:
  Foo() = default;
  ~Foo() = default;                 // prevents stack allocation
};

Prefer ownership idioms (unique_ptr/shared_ptr) or clear factory lifetimes over ad‑hoc delete this unless you really need self-destruction. (microsoft.github.io)

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.