search

Home  >  Q&A  >  body text

c++,为什么一个基类被delete后其虚成员函数还可以被访问

#include <iostream>
using namespace std;


class Base
{
public:
    Base(){};
    virtual void  Base1(){cout << "Base::Base1" << endl;}
    virtual void  Base2(){cout << "Base::Base2" << endl;}
    virtual ~Base(){};
};

int main()
{
    Base*  f = new Base;

    intptr_t* vptr_adress = (intptr_t*)f;
    intptr_t* vptr_func1_adress = (intptr_t*)*vptr_adress;

    typedef void(*FUNC)(void);
    FUNC f1 = (FUNC)*vptr_func1_adress;
    FUNC f2 = (FUNC)*(vptr_func1_adress+1);

    f1();
    f2();

    delete f;

    f1();
    f2();

    system("pause");
    return 0;
}

结果如下

问题如题:为什么在delete后仍然可以访问虚成员函数

大家讲道理大家讲道理2804 days ago388

reply all(2)I'll reply

  • 迷茫

    迷茫2017-04-17 13:31:22

    If you understand the Memory Model of an object, you should know that the function pointed to by the function pointer stored in the object's virtual table does not exist in the object's memory space. For example, you can convert a 0 into a Base*, and then use this Base* to access Base1, and there will be no problem with Base2. Of course, if you use this in a member function, it will break down.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:31:22

    Why can your deleted files still be recovered?
    You have recycled some memory, but you are not clearing all the contents~these memories will still be old contents before writing new contents~

    reply
    0
  • Cancelreply