简体   繁体   中英

VS2013 list initialization

Consider the code

#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();
}

I think this code is guided by $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.

Instead the VS2013 compiler emits all 0xCCCCCCCC implying that it is leaving all elements of b.member as uninitialized. So, it appears it is performing default initialization instead of value initialization.

Please let me know if I am missing something.

What you want to say is this:

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

If B has a (non-default) constructor or any members with constructors, the above code sample of using ={} may generate a compiler error.

Your code sample can be simplified even further.

#include <iostream>

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

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

This produces the output:

-858993460

which is 0xCCCCCCCC in hex, the debug pattern the VC compiler fills memory with in Debug builds. This seems to be a known bug with both VS2012 and VS2013 as reported here .

You can work around the error by defining a constructor that value initializes the data member individually. In your case adding this constructor will result in all elements of member being 0

B() : member{} {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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