gpt4 book ai didi

c++ - 在 C++14 中,在新表达式的维度中使用 double 值是否有效?

转载 作者:IT老高 更新时间:2023-10-28 14:01:20 26 4
gpt4 key购买 nike

在 C++14 中给出以下代码:

void foo() {
double d = 5.0;
auto p1 = new int[d];
}

clang 在没有诊断的情况下编译它,而 gcc 产生以下诊断 (see it live in godbolt):

error: expression in new-declarator must have integral or enumeration type
7 | auto p1 = new int[d];
| ^

我特别标记了这个 C++14,因为在 C++11 模式下,clang 将其视为格式错误并产生以下诊断 (see it live in godbolt):

error: array size expression must have integral or unscoped enumeration type, not 'double'
auto p1 = new int[d];
^ ~

clang 正确吗?如果是这样,C++14 中发生了什么变化以允许这样做?

最佳答案

Clang 是正确的,[expr.new]p6 中的关键词与 C++11 草案中的以下内容不同:

Every constant-expression in a noptr-new-declarator shall be an integral constant expression ([expr.const]) and evaluate to a strictly positive value. The expression in a noptr-new-declarator shall be of integral type, unscoped enumeration type, or a class type for which a single non-explicit conversion function to integral or unscoped enumeration type exists ([class.conv]). If the expression is of class type, the expression is converted by calling that conversion function, and the result of the conversion is used in place of the original expression. …

this in the C++14 draft :

Every constant-expression in a noptr-new-declarator shall be a converted constant expression ([expr.const]) of type std::size_t and shall evaluate to a strictly positive value. The expression in a noptr-new-declarator is implicitly converted to std::size_t. …

在 C++14 中,对 noptr-new-declarator 中的表达式的要求被削弱为不需要完整的、无作用域的枚举或具有单个非显式转换函数到其中一种类型,但只允许隐式转换到 size_t

措辞的变化来自提案A Proposal to Tweak Certain C++ Contextual Conversions, v3 .

关于c++ - 在 C++14 中,在新表达式的维度中使用 double 值是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745158/

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