gpt4 book ai didi

C++14:你能在 constexpr 中调用 new 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:16 25 4
gpt4 key购买 nike

当 C++14 取消对 constexpr 的限制时,它似乎包括以下内容(从 Wikipedia 复制):

Expressions may change the value of an object if the lifetime of that object began within the constant expression function. This includes calls to any non-const constexpr-declared non-static member functions.

这似乎意味着您可以使用 new 创建一个对象,只要您在表达式中 delete 它,它就被允许。

最佳答案

语言律师回答。所有引用 N3797 .

7.1.5/5 状态:

For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.19), the program is ill-formed; no diagnostic required.

跳到 5.19,我们看到:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • ... [lots of bullets]...

  • a new-expression (5.3.4);

  • a delete-expression (5.3.5);

  • ... [lots more bullets]...

所以不:包含 constexpr 函数且无条件调用 newdelete 的程序格式错误,无法诊断必需的。 (然而,如果任何半正经的编译器未能诊断出 constexpr 函数中对 newdelete 的调用,我会感到惊讶,是否需要。)

关于C++14:你能在 constexpr 中调用 new 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21897015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com