What is constexpr in C++?

前端 未结 4 2177
不思量自难忘°
不思量自难忘° 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:04

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

    The second line is a problem because the pointer does not point to a const object. The pointer itself is const.

    Using

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

    solves that problem. However, that will be still a problem if the variables are defined in a function scope.

    constexpr int i = 0;
    constexpr int const* ri = &i;
    
    int main() {}
    

    is a valid program.

    void foo()
    {
       constexpr int i = 0;
       constexpr int const* ri = &i;
    }
    
    int main() {}
    

    is not a valid program.

    Here's what the C++11 standard has to say about address constant expression:

    5.19 Constant expressions

    3 .. An address constant expression is a prvalue core constant expression of pointer type that evaluates to the address of an object with static storage duration, to the address of a function, or to a null pointer value, or a prvalue core constant expression of type std::nullptr_t.

提交回复
热议问题