2

The questions is where to initialize static const member in c++17 or newer? Please consider the following two solutions for initializing a static const member in c++:

Solution 1 (for c++14 or older):

//foo.h: #include <iostream> struct foo{ static const std::string ToBeInitialized; }; 
//foo.cpp #include <iostream> #include "foo.h" const std::string foo::ToBeInitialized{"with a value"}; 

Solution 2 (for c++17 or newer):

//foo.h: #include <iostream> struct foo{ inline static const std::string ToBeInitialized{"with a value"}; }; 

Currently I prefer solution 2 because it is shorter. What are the advantages and disadvanteges of using solution 1 or solution 2?

I am well aware of the fact that there are several questions dealing about static const initialization:

However non of the above questions deal with c++17 or newer explicitly.

1
  • In general (there may be exceptions that I'm not aware), solution 2 will emit a wink linked symbol in every OBJ file, but solution 1 will emit only one symbol in the translation unit (foo.cpp) that holds the definition. With modern compilers, that's not really much of a drawback, other than a little disk space. Assuming no ODR violations. Commented Dec 1, 2020 at 3:46

1 Answer 1

4

As I understand it the difference is that the "non-inline" static variable gets compiled to a single instance while the "inline" one gets compiled to one per translation unit and then eliminated to a single one by the linker. This means the "inline" elimination can occur only within the linked code, it can NOT cross dynamically linked code. I believe a good explanation has been provided in this thread Inline static const vs static const variable . Good luck!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.