Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate initialization of an array of objects with new which compiler is right? [duplicate]

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?

like image 846
Luke Worth Avatar asked Sep 05 '14 00:09

Luke Worth


People also ask

What is aggregate initialization in C++?

(since C++20) Otherwise, if the initializer list is non-empty, the explicitly initialized elements of the aggregate are the first n elements of the aggregate, where n is the number of elements in the initializer list. Otherwise, the initializer list must be empty ({}), and there are no explicitly initialized elements.

What are the two types of array initialization?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

What is aggregate type C++?

Formal definition from the C++ standard (C++03 8.5. 1 §1): An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

What is uniform initialization in C++?

Uniform initialization is a feature in C++ 11 that allows the usage of a consistent syntax to initialize variables and objects ranging from primitive type to aggregates. In other words, it introduces brace-initialization that uses braces ({}) to enclose initializer values.


Video Answer


1 Answers

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.

like image 157
dyp Avatar answered Oct 18 '22 09:10

dyp