A non-static element initializer from another non-static

Very simple question. Is this valid C ++ 11?

struct Foo { int bar = 1; int baz = bar; }; 

GCC (4.7.2) and Clang (3.1) accept it with pedantic settings:

  -std = c ++ 11 -Wall -W -pedantic 

Intel C ++ (13.0.1.117) does not. He barks at int baz = bar; via:

  error: a nonstatic member reference must be relative to a specific object 

Who is right?

If you are wondering, I use this for code like this, where it brings the initialization code closer, rather than moving the last line to the constructor:

 uint8_t colorR = -1; uint8_t colorG = -1; uint8_t colorB = -1; uint8_t colorA = -1; GLubyte RGBAVec[4] = {colorR, colorG, colorB, colorA}; 
+6
source share
1 answer

5.1p12 An identifier that denotes a non-static data element or non-static member function of a class can:

  • as part of class member access (5.2.5), in which an object expression refers to a class of members or a class derived from that class, or
  • to form a pointer to an element (5.3.1) or
  • in mem-initializer for the constructor for this class or for a class derived from this class (12.6.2), or
  • in parentheses or equal initializers for a non-static data element of this class or class derived from this class (12.6.2) or
  • if this id expression denotes a non-static data element and it appears in an unvalued operand.

So yes, this is:

 struct Foo { int bar = 1; int baz = bar; }; 

let's say C ++ 11.

But be careful about order because:

12.6.2p10 In the constructor without delegation, initialization is performed in the following order:

  • Firstly, and only for the constructor of the derived class (1.8) itself, the virtual base classes are initialized in the order that they appear during the first reverse direction from left to right directed acyclic graph of base classes, where "from left to right" is the order in which base classes appear in the base specifier A list of derived class.
  • Then direct base classes are initialized in the order of declaration, as they appear in the list-qualifier-base (regardless of the order of mem-initializers).
  • Then the non-static data members are initialized in the order in which they were declared in the class definition (again, regardless of the order of the mem initializers).
  • Finally, the composite constructor body statement is executed.

So, as stated in the Proposal for initializers of non-static data elements (problem 3):

The third problem is that class search can turn a compile-time error into a temporary error:

 struct S { int i = j; // ill-formed without forward lookup, undefined behavior with int j = 3; }; 

(If not caught by the compiler, I could be indexed using the value undefined j.)

+3
source

All Articles