Search code examples
c++initializationlanguage-lawyerobject-lifetimeaggregate-initialization

Are pointer to a member of this allowed in object initialization?


From Aggregate initialization, set pointer to struct member, is the following code legal:

struct S 
{
  int a;
  int* aptr;
};

S s = { 3, &s.a };

Solution

  • Quote from latest standard draft:

    [basic.scope.pdecl]

    The point of declaration for a name is immediately after its complete declarator ([dcl.decl]) and before its initializer (if any), except as noted below.

    So, yes. The identifier s has already been declared, so it can be used in its initialiser.

    Note that the value of s may not be used until it has been initialised. The value is not used in the example, so this is not a problem.

    I'd also be curious about whether analogous code is valid when the two members of S are in reversed order

    The order of members does not matter.