According to cppreference, std::array
's constructor performs default-initialization when an std::array
is created. However, when I'm doing some test in Visual Studio 12.0, in some circumstances std::array
seems to be performing value-initialization.
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 has indeterminate values while sometimes it has 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;
};
When the constructor is not explicitly defined or arr
is not in the member initializer list, arr
contains indeterminate values.
Container() {} // arr has indeterminate values, same for no constructor case
When arr
is in the member initializer list, arr
contains all zero.
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 member initializer is not implemented
Is the code supposed to be valid according to the new standard of C++? If so, is it just my Visual Studio version does not support it?
To have the same effect, I write the following code. Is there any potential problem in the code? Because I'm not sure if the code is correct.
Container() :
arr( decltype(arr){ 0, 1, 2 } )
{}
P.S. I'm using Microsoft Visual Studio Community 2013.
Aucun commentaire:
Enregistrer un commentaire