Where to initialize static const member in c++17 or newer?

Viewed 589

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 Answers

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!

Related