Reputation: 28893
Is the following legal?
class Aggregate {
public:
int a;
int b;
};
class Class {
public:
Class():
m_aggregate{
3,
// Here, m_aggregate.a is fully constructed, but m_aggregate is not
m_aggregate.a + 5
} {
}
Aggregate m_aggregate;
};
Is it legal to use elements of an aggregate after their lifetime has begun, but before the completion of the constructor of the aggregate as a whole?
Testing with gcc 4.8.2 seems to behave correctly...
Upvotes: 3
Views: 79
Reputation: 477398
I don't think that's legitimate. It is true that the elements of the braced list are initialized in order (i.e. the evaluation of list elements is sequenced, cf. 8.5.4/4), but the aggregate is only constructed after the list has been fully constructed. Cf. 8.5.1:
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.
In order to copy-initialize from something, the original needs to exist first.
Upvotes: 5