[英]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.