+ -
当前位置:首页 → 问答吧 → 条款52的疑问

条款52的疑问

时间:2011-12-05

来源:互联网

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

struct A
{
  A() {throw int(5);}
  virtual ~A() {}
  void operator delete(void *p, size_t N)
  {
  cout<<"调用delete (void*, size_t),N = "<<N<<endl;
  ::operator delete(p);
  }
  void operator delete(void *p, size_t N, const string &)
  {
  cout<<"调用delete (void*, size_t, string),N = "<<N<<endl;
  ::operator delete(p);
  }
  int i;
};

struct B: A
{
  B() {}
  void* operator new(size_t N, const string &)
  {
  cout<<"调用new (size_t, string)"<<endl;
  ::operator new(N);
  }
  double d;
};

int main()
{
  cout<<"sizeof(A) = "<<sizeof(A)<<endl;
  cout<<"sizeof(B) = "<<sizeof(B)<<endl;
  try
  {A *p=new("abc") B;
  delete p;
  }
  catch(int)
  { cout<<"捕捉到"<<endl; }
  cout<<"END";
   
  return 0;
}

虽然派生类没有定义特定的string版opertaor delete,不过基类定义有啊,实现当中是通过怎样的代码来阻止对基类的同名函数的调用的?

作者: yozola   发布时间: 2011-12-05

可能我的代码太长了,都没人有心情去看,那我简单描述一下吧。
构造函数中抛出异常的时候,编译器没有调用对应的operator delete

作者: yozola   发布时间: 2011-12-06