我正在尝试在堆上分配包含非 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 和初始化列表来创建结构吗?