为什么 C++11 不支持 C99 指定的初始化列表?
考虑:
struct Person
{
int height;
int weight;
int age;
};
int main()
{
Person p { .age = 18 };
}
上面的代码在 C99 中是合法的,但在 C++11 中是不合法的.
The code above is legal in C99, but not legal in C++11.
什么是 c++11 标准委员会不支持这样一个方便的功能的理由是什么?
What was the c++11 standard committee's rationale for excluding support for such a handy feature?
推荐答案
C++ 有构造函数.如果只初始化一个成员是有意义的,那么可以通过实现适当的构造函数在程序中表达.这是 C++ 提倡的那种抽象.
C++ has constructors. If it makes sense to initialize just one member then that can be expressed in the program by implementing an appropriate constructor. This is the sort of abstraction C++ promotes.
另一方面,指定初始值设定项功能更多的是公开和使成员易于直接在客户端代码中访问.这会导致诸如拥有一个 18 岁(岁?)但身高和体重为零的人.
On the other hand the designated initializers feature is more about exposing and making members easy to access directly in client code. This leads to things like having a person of age 18 (years?) but with height and weight of zero.
换句话说,指定的初始化器支持公开内部结构的编程风格,并且客户端可以灵活地决定他们希望如何使用该类型.
In other words, designated initializers support a programming style where internals are exposed, and the client is given flexibility to decide how they want to use the type.
C++ 更感兴趣的是将灵活性放在类型的设计者 方面,因此设计者可以轻松正确地使用类型而难以使用不当.让设计者控制如何初始化类型是其中的一部分:设计者确定构造函数、类内初始化器等.
C++ is more interested in putting the flexibility on the side of the designer of a type instead, so designers can make it easy to use a type correctly and difficult to use incorrectly. Putting the designer in control of how a type can be initialized is part of this: the designer determines constructors, in-class initializers, etc.
相关文章