Why constexpr must be static?

独自空忆成欢 提交于 2021-01-27 04:07:04

问题


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

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