Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline std::mutex in header file

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 = {};
like image 511
Loreto Avatar asked Nov 15 '25 16:11

Loreto


1 Answers

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)

like image 200
prog-fh Avatar answered Nov 18 '25 06:11

prog-fh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!