【问题标题】:Inline std::mutex in header file头文件中的内联 std::mutex
【发布时间】:2019-07-03 19:12:36
【问题描述】:

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

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

inline std::mutex mtx;

mtx 是这样构造的吗?

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

inline std::mutex mtx = {};

【问题讨论】:

    标签: c++ c++17 inline-variable


    【解决方案1】:

    在 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; }
    【解决方案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. 
    

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

    【讨论】:

    • 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. 和你说的不冲突吗?
    • @JVApen 我不这么认为,因为为了防止未定义的行为,这些多个定义必须完全相同(一个定义规则)。
    猜你喜欢
    • 1970-01-01
    • 2017-03-28
    • 2013-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    相关资源
    最近更新 更多