Search code examples
c++c++11value-initialization

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.


Solution

  • 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{} {}