Inline std::mutex in header file

1.7k Views Asked by At

I am using a global std::mutex in different cpp files.

Is it okay to declare it in a header file as inline?

inline std::mutex mtx;

Is mtx constructed this way?

Should it be initialized explicitly? As in:

inline std::mutex mtx = {};
2

There are 2 best solutions below

2
prog-fh On BEST ANSWER

In the documentation on inline keyword applied to a variable (C++17) (https://en.cppreference.com/w/cpp/language/inline) it is stated that

2) It has the same address in every translation unit.

and

If an inline function or variable (since C++17) with external linkage is defined differently in different translation units, the behavior is undefined. 

I understand from these sentences that the mutex will actually be unique and correctly initialised (if the only header suggested is used)

1
NathanOliver On

In C++17 and above it is okay and proper to declare mtx as inline. This allows you to have the same variable defined in all the translation units it is in.

Should it be initialized explicitly? As in:

inline std::mutex mtx = {};

That is not needed. std::mutex is default constructable so inline std::mutex mtx; is all you need.


Before we had inline variables what you would have to do is have a header file with

extern std::mutex mtx;

in it and then in a single cpp file have

std::mutex mtx;

in it to actually provide a single definition.