use*_*570 5 c++ undefined-behavior language-lawyer
我遇到了以下主张:
实际上,在计算常量表达式时,需要捕获该语言中所有形式的 UB(尽管标准库中的 UB 不需要捕获)。只有运行时 UB 才可能发生任何事情。
(强调我的)
我的问题是上述说法在技术上正确吗?
在询问用户标准如何强加这一点时,他们引用了expr.const#5.8,其中指出:
5.表达式 E 是核心常量表达式,除非对 E 的计算遵循抽象机 ([intro.execution]) 的规则,将计算以下其中一项:
5.8. 具有 [intro] 到 [cpp] 中指定的未定义行为的操作;
但在阅读了上面的[expr.const#5.8]之后,我无法弄清楚这如何意味着在计算常量表达式时需要捕获语言中所有形式的 UB。那么有人可以澄清这个引文如何支持(如果支持的话)上面引用的评论中提出的主张吗?
我还读过这样的内容:
如果行为未定义,编译器可以接受它,拒绝它,发出警告,并根据标准,甚至在您的计算机上崩溃、挂起或安装病毒。
因此,在我看来(在阅读第一条评论后),常量表达式求值期间的 UB 和运行时 UB 之间存在根本区别。
真相是什么?
\n\ni could not figure out how this implies that all forms of UB in the language are required to be caught when evaluating a constant expression.
\n
Not necessarily for all forms of UB. As per the quoted rule, only if operation is that is evaluated would have undefined behavior as specified in [intro] through [cpp];.
\nNo other UB such as specified in other sections, or UB that isn't caused by evaluation of an operation, prevents an expression from being core constant. There is a clarifying rule:
\n\n\n[expr.const]
\nIf E satisfies the constraints of a core constant expression, but evaluation of E would evaluate an operation that has undefined behavior as specified in [library] through [thread], or an invocation of the va_\xc2\xadstart macro ([cstdarg.syn]), it is unspecified whether E is a core constant expression.
\n
This clarification (including the "as specified in ..." sentence from question) is a resolution to defect report 1952 and the wording is in C++17.
\nTo clarify, the rule causes certain UB to prevent an expression from being core constant. Consider a case where a rule requires an expression to be constant. Here is a an example of such rule:
\n\n\n[dcl.array]
\nRun Code Online (Sandbox Code Playgroud)\nD1 [ constant-expression opt ] attribute-specifier-seq opt \n... The constant-expression shall be a converted constant expression of type std\xe2\x80\x8b::\xe2\x80\x8bsize_\xc2\xadt ([expr.const]). Its value N specifies the array bound, i.e., the number of elements in the array; ...
\n
If some context requires an expression to be constant, then the expression not being constant will violate that rule. In such case this applies:
\n\n\n[intro.compliance.general]
\n如果程序包含违反任何可诊断规则的行为 or an occurrence of a construct described in this document as \xe2\x80\x9cconditionally-supported\xe2\x80\x9d when the implementation does not support that construct, a conforming implementation shall issue at least one diagnostic message.
\n
| 归档时间: |
|
| 查看次数: |
251 次 |
| 最近记录: |