8

尽管我非常喜欢 C++11 中的新特性,但有时我觉得我错过了它的一些微妙之处。

初始化 int 数组工作正常,初始化 Element2 向量工作正常,但初始化 Element2 数组失败。我认为正确的语法应该是未注释的行,但初始化尝试对我来说都没有成功。

#include <array>
#include <vector>

class Element2
{
    public:
            Element2(unsigned int Input) {}
            Element2(Element2 const &Other) {}
};

class Test
{
    public:
            Test(void) :
                    Array{{4, 5, 6}},
                    Array2{4, 5},
                    //Array3{4, 5, 6}
                    Array3{{4, 5, 6}}
                    //Array3{{4}, {5}, {6}}
                    //Array3{{{4}, {5}, {6}}}
                    //Array3{Element2{4}, Element2{5}, Element2{6}}
                    //Array3{{Element2{4}, Element2{5}, Element2{6}}}
                    //Array3{{{Element2{4}}, {Element2{5}}, {Element2{6}}}}
                    {}
    private:
            std::array<int, 3> Array;
            std::vector<Element2> Array2;
            std::array<Element2, 3> Array3;
};

int main(int argc, char **argv)
{
    Test();
    return 0;
}

我在 MinGW 下的 g++ 4.6.1 和 4.6.2 上试过这个。

我应该如何正确地初始化这个数组?是否可以?

4

1 回答 1

7

解决这个问题的正确方法是Array{{4, 5, 6}}. 使用聚合初始化初始化成员时,不能省略大括号。唯一可以省略大括号的情况是在表单声明中

T t = { ... }

So in your case you have to type out all braces: One for the std::array itself, and one for the int array. For Array3, your syntax is correct too, since int can be converted to Element2 implicitly.

From the remaining commented ones, the Array3{{{4}, {5}, {6}}}, Array3{{Element2{4}, Element2{5}, Element2{6}}} and Array3{{{Element2{4}}, {Element2{5}}, {Element2{6}}}} work too, but are more wordy. However conceptionally the Array3{{{4}, {5}, {6}}} one produces the least amount of temporaries on implementations that don't do copy elision (I guess that's irrelevant, but still good to know), even less than the Array3{{4, 5, 6}} one, because instead of copy initialization you use copy list initialization for your Element2, which doesn't produce an intermediary temporary by design.

于 2012-02-05T10:36:48.463 回答