2012-12-13 143 views
6

非常简单的问题。这个有效的C++ 11吗?非静态成员初始化来自另一个非静态

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

GCC(4.7.2)和锵(3.1)既与迂腐设置接受它:

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

英特尔C++(13.0.1.117)没有。它在int baz = bar;与:

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

谁是正确的?

万一你不知道,我用这个像这样的代码,它带来的初始化代码紧密联系起来,而不是最后一行移动到构造函数:

uint8_t colorR = -1; 
uint8_t colorG = -1; 
uint8_t colorB = -1; 
uint8_t colorA = -1; 
GLubyte RGBAVec[4] = {colorR, colorG, colorB, colorA}; 

回答

3

5.1p12 An id-expression that denotes a non-static data member or non-static member function of a class can only be used:

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

所以,是的,这样的:

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

是有效的C++ 11。

但要小心约顺序,因为:

12.6.2p10 In a non-delegating constructor, initialization proceeds in the following order:

  • First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where “left-to-right” is the order of appearance of the base classes in the derived class base-specifier-list.
  • Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).
  • Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
  • Finally, the compound-statement of the constructor body is executed

所以如在Non-static data member initializers proposal(问题3)指定:

A third issue is that class-scope lookup could turn a compile-time error into a run-time error:

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

(Unless caught by the compiler, i might be intialized with the undefined value of j.)

+0

感谢。这看起来很明确。尽管“或从这个阶级派生的阶级”是指什么?如何用派生类的成员初始化成员?派生类尚未声明,因此无法访问它。 –

+0

@Nikos C.“或从该类派生的类”是指“一个括号或等于初始值设定项”,这意味着初始值设定项是一个在dervied类中。基本上我认为这意味着你可以使用父类的非静态数据成员初始化非静态数据成员。这是你理解它的另一种方式,这更让人感觉:) – Drax