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

前端 未结 1 822
谎友^
谎友^ 2021-01-05 14:46

According to cppreference, std::array\'s constructor performs default-initialization when an std::array is created. However, when I\'m doing some t

相关标签:
1条回答
  • 2021-01-05 15:11

    std::array is an aggregate, it does not have constructors (and that's intentional). So when default-initialised, it default-initialises its elements. When value-initialised, it value-initialises them.

    To analyse 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 is default-initialised. arr2 is copy-initialised from a temporary which was initialised with (), i.e. value-initialised.

    Container() {}
    

    This leaves the member arr default-initialised.

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

    This initialises arr using (), which is value-initialisation.

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

    This is legal C++11, but VS 2013 apparently doesn't support it (its C++11 support is incomplete).

    0 讨论(0)
提交回复
热议问题