constexpr with untouched non-constexpr arguments: Who is correct, clang or gcc?

送分小仙女□ 提交于 2019-12-10 15:24:05

问题


I have 4 test cases and I believe that all of them are valid:

constexpr int f(int const& /*unused*/){
    return 1;
}

void g(int const& p){
    constexpr int a = f(p); // clang error, gcc valid

    int v = 0;
    constexpr int b = f(v); // clang valid, gcc valid

    int const& r = v;
    constexpr int c = f(r); // clang error, gcc error

    int n = p;
    constexpr int d = f(n); // clang valid, gcc valid
}

int main(){
    int p = 0;
    g(p);
}

Clang and GCC differ only in the first test case.

I tested with clang 4 & 5 (20170319) and with GCC 7.0.1 (20170221).

If I'm right it would massively simplify the usage of boost::hana in static_assert's.


回答1:


[expr.const]/2:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

  • [...]
  • an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either

    • it is initialized with a constant expression or

    • its lifetime began within the evaluation of e;

  • [...]

Neither condition is satisfied for p or r. Therefore neither f(p) nor f(r) is a core constant expression and hence neither can be used to initialize a constexpr variable. Clang is correct.



来源:https://stackoverflow.com/questions/42997847/constexpr-with-untouched-non-constexpr-arguments-who-is-correct-clang-or-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!