Constexpr运算符new [英] Constexpr operator new
问题描述
是否有可能将new运算符重载为constexpr函数?像这样:
Is it possible to overload the operator new to be constexpr function? Something like:
constexpr void * operator new( std::size_t count );
之所以要在重载的运算符主体中执行constexpr函数,其中count参数值将是输入数据...运算符是由以下方式调用的:
The reason why would be to execute constexpr function within the overloaded operator body where count argument value would be an input data... As the operator is invoked by:
SomeClass * foo = new SomeClass();
数据类型的大小在编译时就知道了,不是吗? (count== sizeof(SomeClass)
)因此,该计数可以视为编译时间常数吗?
The size of the data type is know at compile time, isn’t it? (count== sizeof(SomeClass)
) So the count can be considered as compile time constant?
constexpr void * operator new( std::size_t count )
{
if constexpr ( count >= 10 ) { /* do some compile-time business */ }
}
在此先感谢任何愿意提供帮助的人!
Many thanks in advance to anyone willing to help!
推荐答案
您不能将运算符new
重载为constexpr
,主要问题在于C ++标准指令§9.1.5/1 constexpr
说明符[dcl.constexpr] (重点矿):
You can't overload operator new
to be constexpr
, the main problem is attributed to the C++ standard directive §9.1.5/1 The constexpr
specifier [dcl.constexpr] (Emphasis Mine):
constexpr
说明符应仅应用于 变量或变量模板或函数的声明或 功能模板.用声明的函数或静态数据成员constexpr
说明符隐式是一个内联函数或变量 (9.1.6). 如果函数或函数模板的任何声明具有constexpr
说明符,则其所有声明应包含constexpr
说明符.
The
constexpr
specifier shall be applied only to the definition of a variable or variable template or the declaration of a function or function template. A function or static data member declared with theconstexpr
specifier is implicitly an inline function or variable (9.1.6). If any declaration of a function or function template has aconstexpr
specifier, then all its declarations shall contain theconstexpr
specifier.
也就是说,为了重载运算符new
的所有先前声明也必须为constexpr
,而并非如此,因此将其重载为constexpr
会导致编译时错误.
That is, in order to overload operator new
all its previous declarations must also be constexpr
, which they aren't and thus overloading it as constexpr
you get a compile time error.
这篇关于Constexpr运算符new的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!