繁体   English   中英

下面的代码,它是不正确的NDR还是形成良好?

[英]The code below, is it ill-formed NDR or is it well formed?

Clang接受以下代码,但gcc 拒绝它

void h() { }

constexpr int f() {
    return 1;
    h();
}

int main() {
    constexpr int i = f();
}

这是错误消息:

g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'constexpr int f()':
main.cpp:5:6: error: call to non-'constexpr' function 'void h()'
     h();
     ~^~
main.cpp: In function 'int main()':
main.cpp:9:24: error: 'constexpr int f()' called in a constant expression
     constexpr int i = f();
                       ~^~
main.cpp:9:19: warning: unused variable 'i' [-Wunused-variable]
     constexpr int i = f();

一旦我们考虑[dcl.constexpr] / 5 ,假设f()不是常量表达式,因为它不满足[expr.const] /(4.2) ,这很可能是两个编译器都正确的情况,因为它称为非constexpr函数h 也就是说,代码格式错误,但不需要诊断。

另一种可能性是代码格式正确,因为[expr.const] /(4.2)在这种情况下不适用,因为不评估对f h的调用。 如果是这种情况, gcc是错误的并且clang是正确的。

铿锵是对的。 f()的调用是一个常量表达式,因为永远不会计算对h()的调用,因此[dcl.constexpr] / 5不适用。 f()体中对h()的调用并不是constexpr因为constexpr函数的约束没有说明不允许调用非constexpr函数。 实际上,像下面这样的函数是格式良好的,因为当x为奇数时,对它的调用可以是常量表达式:

constexpr int g(int x) {
    if (x%2 == 0) h();
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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