使用operator new和初始化语法来初始化非POD数组是否可能?

9
我刚刚阅读并理解了在C++ 11中是否可以使用new运算符初始化数组的文章,但它并没有完全解决我的问题。
这段代码在Clang中会导致编译错误:
struct A
{
   A(int first, int second) {}
};
void myFunc()
{
   new A[1] {{1, 2}};
}

我本来期望{{1, 2}}会初始化数组,生成一个只包含一个元素的数组,该元素使用构造参数{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
       ^

为什么这个语法不起作用?

1
еӣ дёәAзҡ„жһ„йҖ еҮҪж•°дёҚжҺҘеҸ—еҲқе§ӢеҢ–еҲ—иЎЁдҪңдёәе”ҜдёҖеҸӮж•°гҖӮ{1, 2}жҳҜдёҖдёӘstd::initializer_listпјҢ(1,2)еҲҷжҳҜдёӨдёӘзӢ¬з«Ӣзҡ„еҸӮж•°пјҢе®ғ们жҳҜйқһеёёдёҚеҗҢзҡ„дёңиҘҝгҖӮ - quant
1
FYI,g++4.9 可以接受这个程序。 - dyp
3
@Arman {1, 2} 是一个花括号初始化列表(braced-init-list)。花括号初始化列表不一定需要调用 initializer_list 构造函数。花括号初始化列表更为通用,它们是统一初始化的一部分(uniform initialization)。 - dyp
1个回答

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的程序。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接