zoukankan      html  css  js  c++  java
  • C++明确规定,不能获取构造函数和析构函数的地址

    C++标准明确规定,不能获取构造函数和析构函数的地址,因此也无法形成指向他们的成员函数指针。

    指向成员函数的指针可以,指向构造函数析构函数的不行。
    因为构造函数和析构函数都是没有返回值的,无法声明一个没有返回值的成员函数指针。

    但是通过汇编代码,有可能获得它,这是代码,但我在VC6上没有能够编译通过:

    #include <iostream>
    using namespace std;
    template <typename T>
    static void* Destruct()//得到T析构函数的地址并返回
    {
    T *p;
    goto getDesAddr;
    desAddr:
    p->~T();
    #ifdef _WIN32 //_MSC_VER //intel格式汇编,windows 平台
    #ifdef _MSC_VER
    __asm{
    ret
    getDesAddr:
    push eax
    mov eax,desAddr //save the address of T::~T()
    mov p,eax
    pop eax
    }
    #endif
    #endif
    return (p);
    }
    
    typedef void(*Fndes)();
    static void executeDestruct(void *addr)//执行addr指向的析构函数
    {
    Fndes exe=reinterpret_cast<Fndes>(addr);
    exe();
    }
    
    
    class A{
    public:
    ~A(){
    cout<<"~A"<<endl;
    }
    };
    void main()
    {
    void*p=Destruct<A>();
    executeDestruct(p);
    }

    参考:

    http://bbs.csdn.net/topics/350168207

  • 相关阅读:
    字串变换
    单词接龙
    二叉搜索树
    搜索专题(未完)
    单调栈
    单调队列练习(切蛋糕&好消息,坏消息)
    队列专题
    滑动窗口/【模板】单调队列
    Linux下如何查看硬件信息?
    Git 居然可以用来跟女神聊天?
  • 原文地址:https://www.cnblogs.com/findumars/p/3746869.html
Copyright © 2011-2022 走看看