我正在尝试一些东西,在堆上分配包含非 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
复制(可能移动)一个 B
, 不会产生任何错误。
我做错了什么吗?我的意思是,我可以使用提供的代码段中的最后一行,但有什么理由不能只使用 operator new 和初始化列表创建结构?
最佳答案
代码应该可以编译并运行。我用 gcc 4.7.0 测试了它,它工作正常,所以这个错误似乎已经修复了。如果您阅读标准中的 8.5.4 List-initialization,他们会说 List initialization can be used as the initializer in a new expression (5.3.4)
。
关于c++ - 在非 pod 结构上使用 operator new + Initializer list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11129145/