10

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?
4
  • Well, copying it wouldn't make much sense. Commented Apr 13, 2014 at 18:40
  • 1
    Much better once in static memory than many times, one in each instance of the struct. Commented Apr 13, 2014 at 18:43
  • 2
    Why would you have a copy of constexpr for each object? Commented Apr 13, 2014 at 18:43
  • @NemanjaBoric constexpr is compile-time only, right? So if that's the case, why would you have one per instance? It wouldn't exist at runtime. Commented Oct 1, 2014 at 22:30

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see nothing wrong with constexpr int n = 10 as it is an integral type every use of n during compilation should be substituted with its value just like in case of define. The syntax is pretty clear, I don't understand why the standard doesn't allow it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.