0

I tried deleting this pointer from constructor, and afterwards when i access private variable through a member function, the variable is fetched correctly.

If I try to delete this again(in constructor or func()), my program crashes. That means this pointer is deleted fine in constructor.

class B
{
    int a;
public:
    B()
    {
        std::cout << this;
        std::cout << "\nConstructor\n";
        delete this;
        a = 5;
        std::cout << "\n" << this;
    }
    ~B()
    {
        std::cout << "Destructor\n";
    }
    void func()
    {
        std::cout << "\n" << a << " Func\n";
    }
};

int main(int argc, char* argv[])
{
    B *b = new B();
    b->func();
    return 0;
}

But calling func() prints correct output. I expected some error due to deleted this. Why the implicit argument of func() is not updated when deleted?

Sunshyn
  • 43
  • 5
  • 2
    Accessing an object after calling `delete this;` is *undefined behaviour* (UB). That means exactly what it says, you are wrong to expect an error. It's one of the commonest beginner misunderstandings, 'I wrote some bad code why isn't it an error?' C++ doesn't work like that. – john Aug 23 '19 at 17:34
  • 1
    What are you trying to achieve? This is undefined behaviour. Anything can happen. – Rosme Aug 23 '19 at 17:34
  • Run it with `valgrind` or any other sanitizer and you'll find your error. – user3427419 Aug 23 '19 at 17:35
  • 1
    UB is not reasonable. It can do anything imaginable, including the worst-case: seemingly working. – Yksisarvinen Aug 23 '19 at 17:35
  • 2
    I can't imagine a scenario where `delete this;` in a constructor can ever work. – François Andrieux Aug 23 '19 at 17:36
  • I think reading the following may be helpful: https://stackoverflow.com/a/6445794/5910058 – Jesper Juhl Aug 23 '19 at 20:06
  • In all my 20+ years of programming in C++, I've never come across deleting a class in the constructor. Why would you delete the object while object construction is occurring? You might as well not have the class. – Thomas Matthews Aug 23 '19 at 20:15

1 Answers1

0

delete this is allowed and just fine. Accessing any members of the class after deleting it however is not allowed and is undefined behavior. Your code appearing to work is one form that UB can take.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122