有效C:第52项以及如何避免隐藏所有正常运算符的新版本和删除版本

在Myer的Effective C中的第52项(自定义新增和删除)结束时,他讨论了在实现自定义版本时如何避免隐藏正常的新版本和删除版本,如下所示:

If you declare any operator news in a
class, you’ll hide all these standard
forms. Unless you mean to prevent
class clients from using these forms,
be sure to make them available in
addition to any custom operator new
forms you create. For each operator
new you make available, of course, be
sure to offer the corresponding
operator delete, too. If you want
these functions to behave in the usual
way, just have your class-specific
versions call the global versions.

An easy way to do this is to create a
base class containing all the normal
forms of new and delete:

class StandardNewDeleteForms {

public:

  // normal new/delete

  static void* operator new(std::size_t size) throw(std::bad_alloc)

  { return ::operator new(size); }

  static void operator delete(void
*pMemory) throw()

  { ::operator delete(pMemory); }



  // placement new/delete

  static void* operator new(std::size_t size, void *ptr) throw()

  { return ::operator new(size, ptr); }

  static void operator delete(void
*pMemory, void *ptr) throw()

  { return ::operator delete(pMemory, ptr); }



  // nothrow new/delete

  static void* operator new(std::size_t size, const std::nothrow_t& nt) throw()

  { return ::operator new(size, nt); }

  static void operator delete(void
*pMemory, const std::nothrow_t&) throw()

  { ::operator delete(pMemory); }

};

Clients who want to augment the
standard forms with custom forms can
then just use inheritance and using
declarations (see Item 33) to get the
standard forms:

class Widget: public StandardNewDeleteForms {           // inherit std forms

public:

   using StandardNewDeleteForms::operator new;  // make those

   using StandardNewDeleteForms::operator delete;       // forms visible



   static void* operator new(std::size_t size,          // add a custom

                             std::ostream& logStream)   // placement new

     throw(std::bad_alloc);



   static void operator delete(void
*pMemory,           // add the corres-

                               std::ostream& logStream) // ponding place-

    throw();                                            // ment delete

  ...

};

为什么要去创建类StandardNewDeleteForms,继承它然后在派生类中说:

using StandardNewDeleteForms::operator new;
using StandardNewDeleteForms::operator delete;

您是否可以完全放弃基类并简单地写入Widget类:

using ::operator new;
using ::operator delete;

实现同样的事情?

最佳答案 这实际上是一个无操作使用.他只是显示了基类new / delete的实现,它将复制正常行为.

通常,如果您正在创建自定义new和delete,那么您将更改该基类中的行为和using :: operator new;不再是等价的.他没有在他的例子中那样做,所以发生的事情稍微不那么清楚了.

点赞