Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?
"; } // or without definition, linker won't complain
   A(int first, int second) { std::cout << "works fine?
"; }
};
int main()
{
   new A[1] {{1, 2}};
}

Live example

g++4.9 also accepts the OP's program without modifications.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...