问题
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