c++ - 怎么解析: constructing unnamed temporary with braced init list

标签 c++ c++11

我最近yet again encountered符号

( const int[10] ){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }

我记得它在 C 和 C++ 中都是允许的,但通过完全不同的语言机制。

我相信在 C++ 中,正式的观点是它是通过显式类型转换 (T) 构造一个未命名的临时对象。 cast-expression 将减少为 static_cast ,通过 C++11 §5.2.9/4 构造一个对象:

an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5)

然而,cast-expression 语法由 C++11 §5.4/2 定义为 unary-expression 或递归的 ( 类型 ID ) cast-expression,其中单个基本情况是简化为 unary-expression

据我所知,braced init-list 不是表达式?

另一种观点可能是它是通过函数表示法进行的显式类型转换,C++11 §5.2.3/3,

a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type

但据我所知,simple-type-specifier 不能涉及括号,而 typename-specifier 涉及关键字 typename ?

最佳答案

根据 C99(嗯,实际上是 N1256,这是之前的草案)6.5.2.5/4:

A postfix expression that consists of a parenthesized type name followed by a brace-enclosed list of initializers is a compound literal. It provides an unnamed object whose value is given by the initializer list.

一些编译器 - at least g++ and clang - 在 C++ 中提供 C99 复合文字作为扩展。语义上,表达式

( const int[10] ){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }

const int[10] 类型的文字: decltype((const int[10]){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }) 实际上是 const int[10]注意: g++ 版本之间对确切类型存在一些分歧:4.9 之前的 g++ 版本表示 decltype((const int[10]){ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 })const int(&)[10]See this demonstration program .

您可以在标准 C++ 中通过函数式表示法进行显式类型转换,但您必须为数组类型定义类型别名,因为函数式表示法需要 simple-type-specifier:

using foo = const int[10];
foo{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

Xeo's general alias template :

template <typename T>
using foo = T;
foo<const int[10]>{ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };

关于c++ - 怎么解析: constructing unnamed temporary with braced init list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24385410/

相关文章:

c++ - 将从唯一指针移动到共享指针也会初始化 enable_shared_from_this

c++ - 在没有其他库的情况下用纯 c/c++ 编写 BMP 图像

c++ - lambda 和相等/不等运算符

c++ - 有没有等同于 void* 的固定大小?

c++ - 跨容器共享对象的最佳方式是什么?

c++ - 如果最后一行不相等则追加

c++ - 我们如何确保传递的 2 个参数被视为第一个和第三个,而第二个和第四个被视为默认值

c++ - 如何在代码块中启用 c++17 支持

C++11:在类构造函数中使用非静态成员函数作为默认参数

C++ 自动类型说明符编译时间