【发布时间】:2019-07-03 19:12:36
【问题描述】:
我在不同的 cpp 文件中使用全局 std::mutex。
可以在头文件中声明为inline吗?
inline std::mutex mtx;
mtx 是这样构造的吗?
是否应该显式初始化?如:
inline std::mutex mtx = {};
【问题讨论】:
标签: c++ c++17 inline-variable
我在不同的 cpp 文件中使用全局 std::mutex。
可以在头文件中声明为inline吗?
inline std::mutex mtx;
mtx 是这样构造的吗?
是否应该显式初始化?如:
inline std::mutex mtx = {};
【问题讨论】:
标签: c++ c++17 inline-variable
在 C++17 及更高版本中,将 mtx 声明为 inline 是可以且正确的。这允许您在它所在的所有翻译单元中定义相同的变量。
是否应该显式初始化?如:
inline std::mutex mtx = {};
这不是必需的。 std::mutex 是默认可构造的,因此您只需要 inline std::mutex mtx;。
在我们拥有内联变量之前,您要做的就是拥有一个带有的头文件
extern std::mutex mtx;
在其中,然后在单个 cpp 文件中有
std::mutex mtx;
在其中实际提供一个定义。
【讨论】:
inline std::mutex &getMtx() { static std::mutex mtx; return 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.
我从这些句子中了解到,互斥锁实际上是唯一的并且已正确初始化(如果使用建议的唯一标头)
【讨论】:
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. 和你说的不冲突吗?