2012-12-13 3 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;의 주소는

입니다. 누가 맞습니까?

궁금 경우

, 나는 그것이 오히려 생성자에 마지막 줄을 이동보다 가깝게 초기화 코드를 제공합니다 같은 코드, 이것을 사용

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입니다.

그러나 것은 순서에 대해주의 하시고 때문에 다음 Non-static data member initializers proposal (문제 3)에 명시된 그래서

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

:

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. 또는 "그 클래스에서 파생 된 클래스"는 "중괄호 또는 등가 이니셜 라이저"를 말하며, 이는 이니셜 라이저가 고아 클래스에있는 것을 의미합니다. 기본적으로 그것은 당신이 부모 클래스의 정적 데이터 멤버가 아닌 정적이 아닌 데이터 멤버를 초기화 할 수 있다는 것을 의미한다고 생각합니다. 그것은 당신이 그것을 이해 한 주위에 다른 방법입니다, 훨씬 더 의미가 있습니다 :) – Drax