在 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;
为了达到同样的目的?
最佳答案
这实际上是一个空操作 using
。他只是展示了基类 new
/delete
的实现,它会复制正常行为。
通常,如果您要创建自定义 new
和 delete
,您会更改该基类和 using::operator new;
中的行为。 code> 将不再等效。他在他的例子中没有这样做,所以不太清楚发生了什么。
关于c++ - 有效 C++ : Item 52 and how to avoid hiding all normal operator new & delete versions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3477270/