c++ - 什么是聚合初始化

标签 c++

“Thinking in Java, 2nd Edition”的第 4 章第 231 页中的“数组初始化”部分有这样的说法:

Initializing arrays in C is error-prone and tedious. C++ uses aggregate initialization to make it much safer. Java has no “aggregates” like C++, since everything is an object in Java. It does have arrays, and these are supported with array initialization.

为什么在 C 语言中容易出错且乏味?聚合初始化是什么意思,为什么它更安全?我遇到了the chapter "Aggregate initialization"在 Bruce Eckel 的“用 C++ 思考”(第 2 版)中,但它并没有让我相信任何事情。

最佳答案

首先,回答主要问题,聚合初始化意味着使用大括号括起来的初始化列表来初始化聚合的所有成员(即数组或结构[在C++中,只有某些类型的结构算作聚合] )。

显然,

int ar[] = { 1 , 2 };

更安全
int ar[2];
ar[0] = 1;
ar[1] = 2;

因为后者为初始化单个元素的索引中的拼写错误和其他错误提供了充足的机会。

看看今天的 C 和 C++,我不清楚作者为什么要区分 C 和 C++。两种语言都支持数组的聚合初始化。

一种可能性是作者引用了旧版本的 C 标准。值得注意的是,在 ANSI C (C89) 中,对聚合初始化的使用有一个重要限制:所有初始化器都必须是常量表达式:

/* This is possible in C89: */
f(int i)
{ int ar[] = { 1 , 2 }; }

/* But this is not
   (because i is not a constant expression):
*/
f(int i)
{ int ar[] = { i , i+1 }; }

这是由于 C89 中的 3.5.7 造成的(引 self 找到的草案 here):

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.

这显然限制了聚合初始化的用处(甚至在 1989 年,我相信许多编译器都实现了扩展以支持非常量表达式的聚合初始化)。

后来的 C 标准版本没有这个限制,我相信 C++ 的标准化版本(从 C++98 开始)从来没有任何这样的限制。

我只能推测,但也许这就是作者的想法?

关于c++ - 什么是聚合初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17712872/

相关文章:

c++ - cocos2d-x 中变量的一次初始化

c++ - Adobe Dreamweaver 扩展

c++ - OpenGL 纹理缓冲区 - GLSL 语法

c++ - 运营商删除 - 如何实现?

C++ map 定义基础

C++ 将派生类的 const 值传递给基本意外行为的构造函数

c++ - 为什么我的图书馆管理程序没有写入文件

c++ - 在我的 C++ 结构中初始化一个空的 unordered_map

c++ - Boost regex、正则表达式、url 和 img

c++ - 制作二维数组时出现运行时错误