3

std::mutex在不同的 cpp 文件中使用全局变量。

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

inline std::mutex mtx;

mtx这样构造的吗?

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

inline std::mutex mtx = {};
4

2 回答 2

3

在 C++17 及更高版本中,声明mtxinline. 这允许您在它所在的所有翻译单元中定义相同的变量。

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

inline std::mutex mtx = {};

那是不需要的。 std::mutex是默认可构造的,所以inline std::mutex mtx;你只需要。


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

extern std::mutex mtx;

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

std::mutex mtx;

在其中实际提供一个定义。

于 2019-07-03T19:21:43.160 回答
2

在关于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. 

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

于 2019-07-03T19:23:30.550 回答