zah*_*pov 2 c++ inheritance memory-management
此页面(来自C++ in action book)显示代码:
class Link
{
friend class FreeList;
public:
Link (Link * pNext, int id)
: _pNext (pNext), _id (id) {}
Link * Next () const { return _pNext; }
int Id () const { return _id; }
// allocator
void * operator new (size_t size)
{
assert (size == sizeof (Link));
return _freeList.NewLink ();
}
void operator delete (void * mem)
{
if (mem)
_freeList.Recycle (mem);
}
static void Purge () { _freeList.Purge (); }
private:
static FreeList _freeList;
Link * _pNext;
int _id;
};
Run Code Online (Sandbox Code Playgroud)
然后说
Class Link有一个静态成员_freeList,由重载的特定于类的运算符new和delete使用.请注意operator new中的断言.它保护我们免受某人为不同的类调用此特定运算符.怎么会发生这种情况?操作员new和delete是继承的.如果从Link派生的类没有覆盖这些运算符,则为派生类调用的new将返回错误大小的对象(基类大小).
这句话是真的吗?我认为将使用正确大小的派生对象调用new.为什么不?
甲new表达将导致分配函数(operator new)与被构造为对象的正确大小被调用.这就是size_t参数的operator new用途.
operator new然而,该示例中的特定实现只能处理统一大小的分配请求.如果派生类没有覆盖operator new 此实现,operator new则会调用它无法处理的大小(也称为"错误").
通常,完全可以为operator new可以处理派生类的分配请求的类编写一个.
| 归档时间: |
|
| 查看次数: |
4915 次 |
| 最近记录: |