简体   繁体   中英

Rule of reordering member declaration in class

I'm reading the c++14 N3797 and I've encountered with 3.3.7/1:

If reordering member declarations in a class yields an alternate valid program under (1) and (2), the program is ill-formed, no diagnostic is required.

There are (1) and (2):

1) The potential scope of a name declared in a class consists not only of the declarative region following the name's point of declaration, but also of all function bodies, default arguments, exception-specifications, and brace-or-equal-initializers of non-static data members in that class (including such things in nested classes).

2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.

That is if we write the following:

class A
{
    int a;
    int b;
}

then the program is ill-formed. Reorering member declaration yields an alternate valid program:

class A
{
    int b;
    int a;
}

Might I don't understand this rule correctly?

The "alternate valid program" is referring to a situation in which each ordering of the elements in the class yields a valid interpretation of the program, but the meaning changes depending on the ordering.

In your case, changing the order of a and b is allowed, but since their relative order can't affect the meaning of the program, the behavior is defined.

For this to happen, you must use a name in the class that has already been defined with some other meaning outside the class. For example:

typedef void *T;

struct whatever {
    T a;
    typedef long T;
};

Here, the relative order of the declaration of a and the typedef of T affects the meaning of the code. As it's written right now, a has type void * , because the global typedef void *T; is in scope when the T a; is parsed.

If, however, we rearranged the two so as:

typedef void *T;

struct whatever {
    typedef long T;
    T a;
};

...the T a; is equivalent to long a; . The meaning of the program is different due to the relative ordering of the two declarations, so the behavior is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM