我最近answered a question处理违反 draft C++14 standard: N4140 的行为section 3.3.7
Class scope paragraph 1
rule 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.
当时规则 3
似乎也相关,它说:
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.
我最初的 react 是规则 3
似乎是多余的,实际上只是对规则 2
的澄清,不涵盖任何尚未涵盖的情况。导致替代有效程序的重新排序也必须违反规则 2
。
那么规则 3
是多余的还是有一些边缘情况需要这两个规则?
最佳答案
根据 Defect Report 1875: Reordering declarations in class scope规则 3
是多余的,建议的解决方案是删除规则 3
,它说:
The need for rule #3 is not clear; it would seem that any otherwise-valid reordering would have to violate rule #2 in order to yield a different interpretation. Taken literally, rule #3 would also apply to simply reordering nonstatic data members with no name dependencies at all. Can it be simply removed?
建议的解决方案是:
Delete the third item of 3.3.7 [basic.scope.class] paragraph 1 and renumber the succeeding items
虽然这个缺陷报告似乎证实了我最初的怀疑,但我还是有一种挥之不去的感觉,也许规则 3
毕竟有点宽泛。 3.3.7
部分包含以下示例:
enum { i = 1 };
class X {
char v[i]; // error: i refers to ::i
// but when reevaluated is X::i
int f() { return sizeof(c); } // OK: X::c
char c;
enum { i = 2 };
};
这违反了规则 2
和 3
但有一个小调整:
enum { i = 1 };
class X {
enum { i = 2 };
char v[i]; // no longer refers to ::i
// but reordering can cause it to refer to ::i again
int f() { return sizeof(c); } // OK: X::c
char c;
};
似乎不再违反规则 2
但肯定似乎违反规则 3
。我认为这个代码示例很麻烦,因为成员的重新排序很容易导致代码返回违反规则 2,但不需要诊断来指示这一点,这使得该代码相当脆弱。
更新
据我所知,规则 3
不适用于 Casey 在评论中提到的这个例子:
class X { int a; int b; };
因为即使有不止一个有效顺序,这种情况也不属于规则 1
和 2
规则 3
要求的规则:
alternate valid program under (1) and (2)
关于c++ - N3936 第 3.3.7/1 节中的规则 3 是否多余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761385/