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

posted @ 2014-05-23 04:32  findumars  Views(2973)  Comments(0Edit  收藏  举报