Constexpr operator new

Mar*_*cký 5 c++ constexpr c++17 if-constexpr

Is it possible to overload the operator new to be constexpr function? Something like:

constexpr void * operator new( std::size_t count );
Run Code Online (Sandbox Code Playgroud)

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(); 
Run Code Online (Sandbox Code Playgroud)

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 */ }
}
Run Code Online (Sandbox Code Playgroud)

Many thanks in advance to anyone willing to help!

101*_*010 4

您不能重载运算符newto be constexpr,主要问题归因于 C++ 标准指令\xc2\xa79.1.5/1constexpr说明符 [dcl.constexpr]强调我的):

\n\n
\n

说明constexpr符仅应用于变量或变量模板的定义或者函数或函数模板的声明。使用\n 说明符声明的函数或静态数据成员 constexpr隐式是内联函数或变量\n (9.1.6)。如果函数或函数模板的任何声明具有\n constexpr说明符,则其所有声明都应包含\n constexpr说明符

\n
\n\n

也就是说,为了重载运算符,new其之前的所有声明也必须是constexpr,但它们不是,因此在constexpr出现编译时错误时会重载它。

\n