获得类析构函数地址并执行析构函数
来源:优易学  2010-1-14 11:40:21   【优易学:中国教育考试门户网】   资料下载   IT书店
  虽然析构函数不是类的函数,但是我们还是有办法获得其地址的。
  #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);
  }

责任编辑:cyth

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训