看More Effective C++中的Item 36. Memory Management-part 2 问题多多

在More Effective中: 

Consider the following code:

class B 
{
public:
  virtual ~B();
  void operator delete  ( void*, size_t ) throw();
  void operator delete[]( void*, size_t ) throw();
  void f( void*, size_t ) throw();
};

class D : public B
{
public:
  void operator delete  ( void* ) throw();
  void operator delete[]( void* ) throw();
};

Why do B's operators delete have a second parameter, whereas D's do not?

The answer is: It's just preference, that's all. Both are usual deallocation functions, not placement deletes. (For those keeping score at home, see section 3.7.3.2/2 in the C++ standard.)

不知道preference是什么? 为什么不是placement delete?

 Continuing with the same piece of code: Which operator delete() is called for each of the following delete expressions? Why, and with what parameters?

 D* pd1 = new D;
delete pd1;

This calls D::operator delete(void*).

B* pb1 = new D; 
delete pb1;

This also calls D::operator delete(void*). Since B's destructor is virtual, of course D's destructor is properly called, but the fact that B's destructor is virtual also implicitly means that D::operator delete() must be called, even though B::operator delete() is not (in fact, cannot be) virtual.

As an aside to those who are interested in how compilers implement these things: The usual method is that the code actually generated for every destructor is given an invisible "when done destroying the object, should I delete it?" flag that is set appropriately (false when destroying an automatic object, true when destroying a dynamic object). The last thing the generated destructor code does is check the flag and, if it's true, call the correct operator delete().[1] This technique automatically ensures the correct behavior, namely that operator delete() appears to act "virtually" even though it is a static function and, therefore, cannot be virtual.

从这里了解到delete时,先找到对应的destructor, 这里自然就是D:~D(),然后在调用operator delete,自然也是D::operator delete(void*). 不管pbl是B*

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值