g++ 4.7 supports array member initialization and I started playing with it.
The code below does not compile.
struct A
{
A(int){};
A(const A&) = delete;
A& operator=(const A&) = delete;
~A(){};
};
struct B
{
B():
a{{0},{1}}
{};
A a[2];
};
B b;
The error message with gcc 4.8 (prerelease) is:
n.cc: In constructor ‘B::B()’:
n.cc:12:20: error: use of deleted function ‘A::A(const A&)’
a{{0},{1}}
^
n.cc:4:8: error: declared here
A(const A&) = delete;
^
Is there a way to make this code work? I can't easily change the contructors,destructor of A. I seem to need a move-constructor or copy-constructor to initialize the array, but this seems counter-intuitive, since all I really want is in-place construction.
It works if I split a[2] in 2 members a0 and a1, and construct them separately. This looks fishy however.
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.
int arrTwoDim[3][2] = {6, 5, 4, 3, 2, 1}; Example 8 defines a two-dimensional array of 3 sub-arrays with 2 elements each. The array is declared and initialized at the same time. The first element is initialized to 6, the second element to 5, and so on.
Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.
Structures and arrays of structures can be initialized by a series of values enclosed in braces, one value per member of the structure.
Within list-initialization (8.5.4p1) of an aggregate (8.5.1), the form of initialization performed on the elements of the aggregate is copy-initialization (8.5.1p2), even if the initialization is direct-list-initialization:
When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order. Each member is copy-initialized from the corresponding initializer-clause.
However, just because the form of initialization performed is copy-initialization doesn't mean that a copy occurs. As per copy-list-initialization of non-copyable types, copy-list-initialization should be identical to direct-list-initialization with the exception that explicit constructors are not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With