在 C++11 中更改了默认初始化的含义? [英] Meaning of default initialization changed in C++11?

查看:23
本文介绍了在 C++11 中更改了默认初始化的含义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++2003 8.5/5 说:

C++2003 8.5/5 says:

默认初始化一个 T 类型的对象意味着:

To default-initialize an object of type T means:

——如果 T 是非 POD 类类型(第 9 条),则调用 T 的默认构造函数(初始化为如果 T 没有可访问的默认构造函数,则格式错误);

— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

——如果 T 是一个数组类型,每个元素都是默认初始化的;

— if T is an array type, each element is default-initialized;

——否则,对象被零初始化.

[强调添加.]

C++2011 标准将最后一项更改为

The C++2011 standard changed that last item to

—否则,不执行初始化.

对于某些程序来说,这似乎是一个重大变化.这是故意的吗?

This seems like it would be a breaking change for some programs. Was this intentional?

编辑

这里有一些代码可以激发这个问题:

Here's some code to motivate this question:

class Foo {
  public:
    Foo() : m_values() {}

    int m_values[3];
};

在 C++11 之前,我认为在默认构造函数中明确提及 m_valuesdefault-initialize 该数组.由于数组的元素是标量,我预计这意味着值都设置为 0.

Before C++11, I thought the explicit mention of m_values in the default constructor would default-initialize that array. And since the elements of the array are scalar, I expected that to mean the values were all set to 0.

在 C++11 中,似乎不再保证会发生这种情况.但也许,正如 Mooing Duck 在评论中指出的那样,也许这不再是默认初始化的情况,而是保留预期行为的其他形式.欢迎引用.

In C++11, it seems there's no longer a guarantee that this will happen. But maybe, as Mooing Duck pointed out in the comments, perhaps this is no longer a case of default initialization but some other form which preserves the expected behavior. Citations welcome.

推荐答案

最终效果差不多.在 C++03 中,default-initialize 的使用仅限于非 POD 类类型,因此最后一点从未应用.在 C++11 中,该标准通过消除使用默认初始化的条件来简化措辞,并更改默认初始化的定义以涵盖所有情况,以对应之前发生的情况.

The final effects are almost the same. In C++03, the use of default-initialize was restricted to non-POD class type, so the last point never applied. In C++11, the standard simplifies the wording by eliminating the condition with regards to where default-initialization was used, and changes the definition of default-initialization to cover all of the cases in a way to correspond what happened before.

这篇关于在 C++11 中更改了默认初始化的含义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆