0

I run this code snippet to test the problem:

#include <iostream>
#include <functional>
using namespace std;

class A
{
private:
    int i;

public:
    A(): i(0) {}    

    void doSomething()
    {
        cout << "do something " << i << endl;
    }
};

int main() {

    A* a = new A();
    function<void()> func = std::bind(&A::doSomething, a);

    delete a;
    a = nullptr;

    func();

    return 0;
}

And got the output:

do something 0

Could anyone help me explain why we can call an object method after deleted the object ?

T.C.
  • 133,968
  • 17
  • 288
  • 421
thenewvu
  • 1
  • 1
  • 3
    The behavior is undefined, which means that one of the allowed behaviors is your function being called. – Anton Savin Feb 01 '15 at 18:31
  • Related: http://stackoverflow.com/questions/2505328/calling-class-method-through-null-class-pointer – Anton Savin Feb 01 '15 at 18:33
  • @quantdev Lazy gcc devs! Make us time travel, dammit! – Pradhan Feb 01 '15 at 18:33
  • When you created `func` it stored the address of `A::doSomething`. After calling `delete` on `a`, the address still remains for `A::doSomething`. `delete` doesn't wipe the memory of `a`. But this is undefined. – James Moore Feb 01 '15 at 18:36
  • 2
    `Could anyone help me explain why we can call an object method after deleted the object ` If you have your drivers license suspended, does that mean you can't physically get into a car and drive it? – PaulMcKenzie Feb 01 '15 at 18:41
  • thank you. shooting myself in the foot ... again :)) – thenewvu Feb 01 '15 at 18:42

0 Answers0