2

After reading this and this I still feel confused about this kind of expressions:

static constexpr int = 0; 

AFAIK, in C++:

  • static ensures life-time memory address along whole execution and safe initialization with concurrent threads
  • constexpr ensures time-compilation evaluation as rvalue, which means it shall have no memory address

They look contradictory to me. static ensures the variable will have a long-time memory address whereas constexpr ensures the opposite assumption. Surprisingly, the discussion in the first link mentions this:

constexpr int x = 3; const int* p = &x; 

How can we even obtain the memory address of x if it is an rvalue?

Could anyone explain it?

7
  • Could you be more explicit whether your are you asking about local scope static or namespace scope static? They have a different meaning and your stated understanding doesn't apply to both. Commented Nov 16, 2020 at 10:02
  • I don't believe constexpr and value category (evaluation as rvalue) has any connection. Commented Nov 16, 2020 at 10:06
  • My question comes from seeing many class members declared static constexpr, I am not sure which kind that should be. In any case, could you briefly explain both? Commented Nov 16, 2020 at 10:06
  • Your first link specifically contradicts a constexpr variable having no address. Commented Nov 16, 2020 at 10:08
  • @Victor Static class members are even more different form other static. You should specify your question. Commented Nov 16, 2020 at 10:10

1 Answer 1

2

static has a number of meanings. In classes (per your comment), it means that the member is associated with the class, and not a specific instance (object) of that class.

For a constexpr, that makes a lot of sense. That's typically initialized by a value known to the compiler, and not from ctor arguments.

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

2 Comments

Have I understood you correctly? static ensures that there is only one variable for all objects whereas constexpr ensures that its initialization is done at compilation time. Thanks.
@Victor: Yes, exactly. (Also, there's one static variable even if there are zero objects).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.