4

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 = {};
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
Loreto
  • 674
  • 6
  • 20

2 Answers2

3

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.

Community
  • 1
  • 1
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • There was also the static function variable approach: `inline std::mutex &getMtx() { static std::mutex mtx; return mtx; }`. – Arne Vogel Jul 04 '19 at 07:08
3

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)

prog-fh
  • 13,492
  • 1
  • 15
  • 30
  • Doesn't `Because the meaning of the keyword inline for functions came to mean "multiple definitions are permitted" rather than "inlining is preferred", that meaning was extended to variables.` conflict with what you say? – JVApen Jul 03 '19 at 20:26
  • @ JVApen I don't think so, because, in order to prevent undefined behaviour, those multiple definitions have to be exactly the same (one-definition-rule). – prog-fh Jul 03 '19 at 20:31