我刚刚阅读并理解了
Is it possible to initialise an array in C++ 11 by using new operator,但这并不能解决我的问题.
struct A { A(int first,int second) {} }; void myFunc() { new A[1] {{1,2}}; }
我预计{{1,2}}用单个元素初始化数组,然后使用构造函数args {1,2}进行初始化,但是我收到此错误:@H_403_3@
error: no matching constructor for initialization of 'A' new A[1] {{1,2}}; ^ note: candidate constructor not viable: requires 2 arguments,but 0 were provided A(int first,int second) {} ^ note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument,but 0 were provided struct A ^
为什么这个语法不起作用?@H_403_3@
解决方法
这似乎是
clang++ bug 15735.声明默认构造函数(使其可访问并且不被删除),并且程序编译,即使未调用默认构造函数:
#include <iostream> struct A { A() { std::cout << "huh?\n"; } // or without definition,linker won't complain A(int first,int second) { std::cout << "works fine?\n"; } }; int main() { new A[1] {{1,2}}; }
Live example@H_403_3@