Does std :: array produce default-initialize or value-initialize?

According to cppreference , the constructor std::array

does default initialization on creation std::array

. However, when I do some tests in Visual Studio 12.0 std::array

, it seems to do value initialization in some cases .

std::array<int, 3> arr1;  // gives me some garbage values, as expected
auto arr2 = std::array<int, 3>();  // gives me three 0, value-initialize?

      

Also, when std::array

is a member of a class, sometimes it is undefined and sometimes it is all zero.

class Container {
public:
    Container() ...

    int& operator[](size_t i) { return arr[i]; }    
    size_t size() { return ARR_SIZE; }

private:
    static const size_t ARR_SIZE = 3;
    std::array<int, ARR_SIZE> arr;
};

      

If the constructor is not explicitly defined or is arr

not in the member initializer list, arr

contains undefined values.

Container() {}  // arr has indeterminate values, same for no constructor case

      

Contains all zero when arr

in the member initializer list arr

.

Container():
    arr()  // arr contains 0, 0, 0
{}

      

Also, when I write the following code, I get an error.

Container() :
    arr{ 0, 1, 2 }
{}

      

g: \ cppconsole \ cppconsole \ main.cpp (89): error C2797: "Container :: arr": list initialization inside member initializer list or non-static data initializer not implemented

Is the code valid according to the new C ++ standard? If so, is it just my version of Visual Studio that doesn't support it?

To have the same effect, I am writing the following code. Is there a potential problem in the code? Because I'm not sure if the code is correct.

Container() :
    arr( decltype(arr){ 0, 1, 2 } )
{}

      

PS I am using Microsoft Visual Studio Community 2013.

+3


source to share


1 answer


std::array

is an aggregate, it has no constructors (and this is by design). So when default initialized, it initializes its elements by default. When a value is initialized, it initializes their value.

Parse your code:

std::array<int, 3> arr1;  // gives me some garbage values, as expected
auto arr2 = std::array<int, 3>();  // gives me three 0, value-initialize?

      

arr1

initialized by default. arr2

initialized with a copy from a temporary, initialized with ()

, that is, initialized with a value.

Container() {}

      



As a result, the element arr

is initialized by default.

Container():
    arr()  // arr contains 0, 0, 0
{}

      

It initializes arr

using ()

which is value initialization.

Container() :
    arr{ 0, 1, 2 }
{}

      

This is legal C ++ 11, but VS 2013 does not seem to support it (its support in C ++ 11 is incomplete).

+6


source







All Articles