9

Is there any difference between static constexpr and constexpr when used inside a function's body?

int SomeClass::get(const bool b) { static constexpr int SOME_CONSTANT = 3; constexpr int SOME_OTHER_CONSTANT = 5; if(b) return SOME_CONSTANT; else return SOME_OTHER_CONSTANT; } 
1
  • I'm looking for any difference inside this function. Because, I guess that everything would be different if they were declared in a compile-time executed, i.e. constexpr, function. Commented Jan 15, 2022 at 10:47

1 Answer 1

7

The main difference between those two declarations is the lifetime of the objects. When writing the question, I thought that using constexpr instead of const would place that object into the .rodata section. But, I was wrong. The constexpr keyword, here, only provides that the object can be used at compile-time functions. So, the object is actually created in the stack during run-time and destroyed when leaving the function's body. On the other hand, the static constexpr object is an object placed in the .rodata section. It is created at the first time we call the wrapping function. In addition, thanks to the constexpr, it is also available during compile-time.

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

1 Comment

To extend the information: Since C++11 if the static variable has a non-trivial constructor, the compiler must ensure thread-safe initialization (using mutexes or atomic operations) so using static may introduce some overhead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.