繁体   English   中英

VS2013列表初始化

[英]VS2013 list initialization

考虑代码

#include "stdafx.h"
#include <Windows.h>
#include <iostream>

struct B
{
public:
    void f() { for (auto &v : member) { std::cout << v << std::endl; } }
private:
    int member[100];
};

int main()
{
    B b{};
    b.f();
}

我认为这段代码由$ 8.5.4 / 3指导

List-initialization of an object or reference of type T is defined as follows:
— If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.

相反,VS2013编译器会发出所有0xCCCCCCCC,这意味着它将b.member的所有元素都保留为未初始化状态。 因此,似乎它正在执行默认初始化而不是值初始化。

如果我缺少什么,请告诉我。

您想说的是:

int main()
{
    B b = {};  // = {} expresses that you want to zero-init the member vars
    b.f();
}

如果B具有(非默认)构造函数或具有构造函数的任何成员,则上面使用={}代码示例可能会生成编译器错误。

您的代码示例可以进一步简化。

#include <iostream>

struct B
{
public:
    void f() { std::cout << member << std::endl; }
private:
    int member;
};

int main()
{
    B b{};
    b.f();
}

产生输出:

-858993460

十六进制为0xCCCCCCCC ,这是VC编译器在Debug版本中填充内存的调试模式。 如此处报道,这似乎是VS2012和VS2013的已知错误。

您可以通过定义一个值分别初始化数据成员的构造函数来解决该错误。 在您的情况下,添加此构造函数将导致member所有元素均为0

B() : member{} {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM