如何防止通过“new”运算符分配类? (我想确保我的RAII类总是分配在堆栈上。) [英] How do I prevent a class from being allocated via the 'new' operator? (I'd like to ensure my RAII class is always allocated on the stack.)
本文介绍了如何防止通过“new”运算符分配类? (我想确保我的RAII类总是分配在堆栈上。)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想确保我的RAII类始终分配在堆栈上。
I'd like to ensure my RAII class is always allocated on the stack.
如何防止通过'new'运算符分配类?
How do I prevent a class from being allocated via the 'new' operator?
推荐答案
所有你需要做的是声明类的新运算符private:
All you need to do is declare the class' new operator private:
class X
{
private:
// Prevent heap allocation
void * operator new (size_t);
void * operator new[] (size_t);
void operator delete (void *);
void operator delete[] (void*);
// ...
// The rest of the implementation for X
// ...
};
使'operator new'私有有效地防止类外的代码使用'new'创建实例。
Making 'operator new' private effectively prevents code outside the class from using 'new' to create an instance of X.
要完成这些,你应该隐藏'operator delete'和两个操作符的数组版本。
To complete things, you should hide 'operator delete' and the array versions of both operators.
因为C ++ 11你还可以显式地删除函数:
Since C++11 you can also explicitly delete the functions:
class X
{
// public, projected, private ... does not matter
static void *operator new (size_t) = delete;
static void *operator new[] (size_t) = delete;
static void operator delete (void*) = delete;
static void operator delete[](void*) = delete;
};
相关问题: