Is it possible to initialise an array of non-POD with operator new and initialiser syntax?

折月煮酒 提交于 2019-12-29 07:34:07

问题


I have just read and understood Is it possible to initialise an array in C++ 11 by using new operator, but it does not quite solve my problem.

This code gives me a compile error in Clang:

struct A
{
   A(int first, int second) {}
};
void myFunc()
{
   new A[1] {{1, 2}};
}

I expected {{1, 2}} to initialise the array with a single element, in turn initialised with the constructor args {1, 2}, but I get this error:

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
       ^

Why does this syntax not work?


回答1:


This seems to be clang++ bug 15735. Declare a default constructor (making it accessible and not deleted) and the program compiles, even though the default constructor is not called:

#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 also accepts the OP's program without modifications.



来源:https://stackoverflow.com/questions/25676935/is-it-possible-to-initialise-an-array-of-non-pod-with-operator-new-and-initialis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!