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

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

问题描述

C ++ 2003 8.5 / 5说:


要初始化为默认初始化意味着:



- 如果T是非POD类类型(第9节),则调用T的默认构造函数(初始化为
ill-如果T没有可访问的默认构造函数);



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



- 否则,对象为零初始化




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



这似乎是对一些程序的一个突破性的改变。这是有意的吗?



编辑



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

int m_values [3];
};

在C ++ 11之前,我认为明确提到 m_values 在默认构造函数中将默认初始化该数组。因为数组的元素是标量的,我预计这意味着值都设置为0.



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

解决方案

最终效果几乎相同。在C ++ 03中,使用 default-initialize 被限制为非POD类类型,因此最后一个点从不应用。在C ++ 11中,标准通过消除关于使用默认初始化的条件来简化措辞,并改变默认初始化的定义以覆盖所有情况,从而对应于之前发生的情况。 p>

C++2003 8.5/5 says:

To default-initialize an object of type T means:

— 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);

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

— otherwise, the object is zero-initialized.

[Emphasis added.]

The C++2011 standard changed that last item to

— otherwise, no initialization is performed.

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

Edit

Here's some code to motivate this question:

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

    int m_values[3];
};

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.

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.

解决方案

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天全站免登陆