c++ - N3936 第 3.3.7/1 节中的规则 3 是否多余?

标签 c++ scope language-lawyer c++14

我最近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 };
};

这违反了规则 23 但有一个小调整:

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; };

因为即使有不止一个有效顺序,这种情况也不属于规则 12 规则 3 要求的规则:

alternate valid program under (1) and (2)

关于c++ - N3936 第 3.3.7/1 节中的规则 3 是否多余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761385/

相关文章:

c++ - 由 placement-new 创建的普通类型的生命周期从什么时候开始?

c++ - 成员函数 Outer::f() 不是类 Outer::Inner 的 friend 。为什么?

c++ - 函数模板的部分特化

c++ - OpenCV RHO 单应性方法不适用于 perspectiveTransform

PHP 和函数作用域

r - 自定义环境中的范围(功能)

具有 C++ 作用域的 Emacs 点符号

c++ - gcov 报告的析构函数中的分支是什么?

c++ - 针对 GNU++98/libstdc++ 编译的应用程序能否链接到针对 C++11/libc++ 构建的 dylib?

c++ - int a[] = {1,2,};为什么允许在初始化列表中使用尾随逗号?