1

我正在尝试在堆上分配包含非 pod 成员的结构并使用初始化列表初始化它们。但是,编译器在我的代码中遇到了错误。这个片段重现了它:

#include <vector>

struct A {
    int a;
};

struct B {
    int a;
    std::vector<int> b;
};

int main() {
    std::vector<int> some_vec;
    A a = {1}; // OK
    A b = A{1}; // OK
    A *c = new A{1}; // OK(leaks, NP)
    B d = {1, some_vec}; // OK
    B e = B{1, some_vec}; // OK

    B *f = new B{1, some_vec}; // Fails to compile

    B *g = new B({1, some_vec}); // OK
}

(我知道泄漏,我知道,这只是一个测试片段)

指出的行在 GCC 4.6.3 上无法编译,出现以下错误:

test.cpp: In function ‘int main()’:
test.cpp:19:29: error: no matching function for call to ‘B::B(<brace-enclosed initializer list>)’
test.cpp:19:29: note: candidates are:
test.cpp:7:8: note: B::B()
test.cpp:7:8: note:   candidate expects 0 arguments, 2 provided
test.cpp:7:8: note: B::B(const B&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided
test.cpp:7:8: note: B::B(B&&)
test.cpp:7:8: note:   candidate expects 1 argument, 2 provided

显然编译器无法使用提供的初始化列表初始化我的结构。奇怪的是,产生错误的那一行之后的下一行(据我所知)只是B从使用相同初始化列表构造的另一行复制(可能移动)a,不会产生任何错误。

我做错了什么吗?我的意思是,我可以使用提供的代码段中的最后一行,但是有什么理由不能只使用 operator new 和初始化列表来创建结构吗?

4

1 回答 1

2

代码应该可以编译和工作。我用 gcc 4.7.0 对其进行了测试,它工作正常,所以似乎已经修复了这个错误。如果您阅读标准中的 8.5.4 列表初始化,他们会说List intialization can be used as the initializer in a new expression (5.3.4).

于 2012-06-20T23:13:33.917 回答