Is `const constexpr` on variables redundant?

匆匆过客 提交于 2021-01-21 03:52:05

问题


cppreference states that:

A constexpr specifier used in an object declaration or non-static member function (until C++14) implies const.


Does "object declaration" mean "any variable declaration"?

I.e. is

constexpr const int someConstant = 3;

equivalent to

constexpr int someConstant = 3;

in C++11, C++14 and C++17?


回答1:


In declarations with primitives, such as the one in your example, const is indeed redundant. However, there may be odd situations where const would be required, for example

constexpr int someConstant = 3;
constexpr const int *someConstantPointerToConstant = &someConstant;

Here, someConstantPointerToConstant is both a constexpr (i.e. it's known at compile time, hence constexpr) and it is also a pointer to constant (i.e. its object cannot be changed, hence const). The second declaration above would not compile with const omitted (demo).




回答2:


const is redundant in const constexpr for objects.

Does "object declaration" mean "any variable declaration"?

It does.

As per cppreference, a variable or a constant is an object:

A variable is an object or a reference that is not a non-static data member, that is introduced by a declaration.



来源:https://stackoverflow.com/questions/50609668/is-const-constexpr-on-variables-redundant

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