0

I'm trying to figure out how class pointers work, here example code:

#include <iostream>

class A {
public:
        void m(int x) {
                std::cout << "hello " << x << std::endl;
        }
};

int main() {

        A *a = new A();

        for (int i = 1; i < 9; ++i) { a->m(i); }

        delete a;

        a->m(123);

        return 0;

}

Why a->m(123); works after delete a;?

  • 3
    It's a manifestation of undefined behaviour, that's all. C++ gives you the ability to shoot yourself in the foot. – Bathsheba Jan 28 '20 at 10:02
  • I think, there should be crash, its worked for me as well. – Build Succeeded Jan 28 '20 at 10:02
  • 1
    @Mannoj: Says who? The C++ standard? You? – Bathsheba Jan 28 '20 at 10:02
  • 1
    Does this answer your question? [Delete calling destructor but not deleting object?](https://stackoverflow.com/questions/18990524/delete-calling-destructor-but-not-deleting-object) – adziri Jan 28 '20 at 10:03
  • 1
    Because using a deleted pointer is [undefined behavior](https://en.cppreference.com/w/cpp/language/ub). That means anything goes. Don't try to reason about whether it should crash or fail or work. – patatahooligan Jan 28 '20 at 10:03
  • by pure chance, it is undefined behavior. @Mannoj, it is not necessary to crash. In release builds, this will usually work as if `a` was not deleted at all. – Zdeslav Vojkovic Jan 28 '20 at 10:03
  • @ZdeslavVojkovic: "Usually"? Do you have statistical evidence to back this up? – Bathsheba Jan 28 '20 at 10:05
  • Even the `std::cout << hello " << x << std::endl;` might be discarded. – Jarod42 Jan 28 '20 at 10:06
  • @Jarod42: Some compilers will detect UB on the only control path and optimise to `int main(){}` – Bathsheba Jan 28 '20 at 10:07
  • @Bathsheba, just a sec, I will do a scientific research to provide you with stats, be right back :) But yes, this exact program will usually work as if there is no huge bug in it. – Zdeslav Vojkovic Jan 28 '20 at 10:19

1 Answers1

3

Accessing memory/object (through a pointer), which is deleted/released/freed is undefined behaviour. You can not expect any reliable things to happen.

P0W
  • 46,614
  • 9
  • 72
  • 119