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

标签 c++ c++14 language-lawyer new-expression

在 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/

相关文章:

C:结构、 union 和枚举的通用术语?

c++ - 获取 C# 输出字符串参数值到 C++ BSTR*?

c++ - 如何获取变量以打印字符串

c++ - simple_type_specifier 不支持 nullptr_type

c++ - 如何使用 boost.asio 解析 ftp 站点?

c++ - 在 c++ 中, `expressions` 只允许在全局范围内用于初始化全局对象。我在哪里可以在标准中找到它?

c++ - 使用 move ctor 的 constexpr 对象的 constexpr 数组

c++ - Lambda 重新初始化 vector - 为什么它有效?

c++ - 函数尝试 block 和 noexcept

c++ - 嵌套在函数中的函数声明的命名空间