问题
An attempt to create a member of a struct with constexpr attribute without being static result in a compiler error(see below). Why is that? for a single constant value will I have this value in memory until program is terminatted instead of just scope of struct? should I back to use a macro?
struct foo
{
constexpr int n = 10;
// ...
};
error: non-static data member cannot be constexpr; did you intend to make it static?
回答1:
I don't know the official rational. But surely it could lead to confusion. I, for one, can't see what it means for a non-static data member to be constexpr
. Are you able to do the following?
struct foo {
constexpr int n = 10;
constexpr foo() { }
constexpr foo(int n):n(n) { } // overwrite value of n
};
Or does it mean that the initializer must be constant always, i.e you are not allowed to write the above (because n
is not constant/could potentially non-constant) but allowed to say
foo f = { 10 };
The rule that constexpr int n
is simply ill-formed rather than being implicitly static
seems good to me, as its semantics would not be clear IMO.
来源:https://stackoverflow.com/questions/23046775/why-constexpr-must-be-static