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.

BlueTune
  • 1,023
  • 6
  • 18
  • 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. – Eljay Dec 01 '20 at 03:46

1 Answers1

3

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!