constexpr const vs constexpr variables?

后端 未结 3 2090
太阳男子
太阳男子 2020-12-02 18:12

It seems obvious that constexpr implies const and thus it is common to see:

constexpr int foo = 42; // no const here

However if you write:<

3条回答
  •  广开言路
    2020-12-02 18:59

    The issue is that in a variable declaration, constexpr always applies the const-ness to the object declared; const on the other hand can apply to a different type, depending on the placement.

    Thus

    constexpr const int i = 3;
    constexpr int i = 3;
    

    are equivalent;

    constexpr char* p = nullptr;
    constexpr char* const p = nullptr;
    

    are equivalent; both make p a const pointer to char.

    constexpr const char* p = nullptr;
    constexpr const char* const p = nullptr;
    

    are equivalent. constexpr makes p a const pointer. The const in const char * makes p point to const char.

提交回复
热议问题