【问题标题】:Is it possible to initialise an array of non-POD with operator new and initialiser syntax?是否可以使用 operator new 和初始化器语法初始化非 POD 数组?
【发布时间】: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


【解决方案1】:

这似乎是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

g++4.9 也接受 OP 的程序,无需修改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2022-08-14
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多