我刚刚阅读并理解Is it possible to initialise an array in C++ 11 by using new operator,但它并没有完全解决我的问题。
这段代码在Clang中给出了一个编译错误:
struct A
{
A(int first, int second) {}
};
void myFunc()
{
new A[1] {{1, 2}};
}
我希望{{1,2}}使用单个元素初始化数组,然后使用构造函数args {1,2}进行初始化,但是我收到此错误:
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
^
为什么这种语法不起作用?
答案 0 :(得分:12)
这似乎是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}};
}
g ++ 4.9也接受OP的程序而不做任何修改。