What is constexpr in C++?

前端 未结 4 2172
不思量自难忘°
不思量自难忘° 2021-02-07 07:48

I am really confused about a constexpr concept, as I have read constexpr is evaluated at compile time, so it is useful for performance optimization ver

4条回答
  •  伪装坚强ぢ
    2021-02-07 08:19

    Re

    if I replaced the constexpr word with const all above worked correctly."

    A const int* essentially means (const int)*, except that you can't use parentheses that way. A constexpr int* means constepxr (int*) (ditto note).

    This is because constexpr is not part of the type, you can't name the type constexpr int, say, while const is part of the type.

    Instead of

    constexpr int i = 0;
    constexpr int& ri = i;
    

    which attempts to declare a constexpr reference to non-const, just write

    constexpr int i = 0;
    constexpr int const& ri = i;
    

    You can read that backwards as ri is a reference to a const int which is constexpr (evaluated at compile time).


    Addendum:

    It ¹appears that C++14 requires local non-static constexpr objects to have automatic storage duration, modulo the as-if rule for optimization.

    To cater for this, i.e. to make the code portable across compilers, if the above declarations appear locally in a function, add static to ensure static storage duration for the object that one refers to:

    void oops()
    {
        static constexpr int i = 0;      // Necessary with some compilers.
        constexpr int const& ri = i;
    }
    

    Otherwise it may not compile with e.g. g++, and it's probably what the C++14 and C++11 standards require, by omission of suitable constraints on constexpr.

    Notes:
    ¹ See the discussion of R. Sahu's answer.

提交回复
热议问题