在头文件中内联 std::mutex

Inline std::mutex in header file

我在不同的 cpp 文件中使用全局 std::mutex

可以在头文件中声明为inline吗?

inline std::mutex mtx;

mtx是这样构造的吗?

是否应该显式初始化?如:

inline std::mutex mtx = {};

在 C++17 及更高版本中,将 mtx 声明为 inline 是正确的。这允许您在它所在的所有翻译单元中定义相同的变量。

Should it be initialized explicitly? As in:

inline std::mutex mtx = {};

不需要。 std::mutex 是默认可构建的,所以 inline std::mutex mtx; 就是您所需要的。


在我们拥有内联变量之前,您需要做的是拥有一个包含

的头文件
extern std::mutex mtx;

在其中,然后在单个 cpp 文件中有

std::mutex mtx;

其中实际上提供了一个定义。

在关于 inline 应用于变量的关键字 (C++17) 的文档中 (https://en.cppreference.com/w/cpp/language/inline) 据称

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

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

我从这些句子中了解到,互斥锁实际上是唯一的并且正确初始化(如果只使用 header 建议)