Constexpr运算符new [英] Constexpr operator new

查看:129
本文介绍了Constexpr运算符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 the constexpr specifier is implicitly an inline function or variable (9.1.6). If any declaration of a function or function template has a constexpr specifier, then all its declarations shall contain the constexpr 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆