【发布时间】:2016-03-03 13:15:09
【问题描述】:
我刚刚阅读并理解了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
^
为什么这个语法不起作用?
【问题讨论】:
-
因为
A不接受初始化列表作为其构造函数的唯一参数。{1, 2}是std::initializer_list,(1,2)是两个独立的参数,它们是非常不同的东西。 -
仅供参考,g++4.9 接受这个程序。
-
@Arman
{1, 2}是一个 braced-init-list。 Braced-init-lists 不必调用initializer_list构造函数。 Braced-init-lists 更通用,它们是统一初始化的一部分。
标签: c++ arrays c++11 clang initializer-list