<mutex> 如何在没有互斥体实例的情况下lock_guard构造函数进行编译?

How lock_guard<mutex> constructor can be compiled fine without mutex instance?

本文关键字:lock 情况下 guard 构造函数 编译 实例 gt mutex lt      更新时间:2023-10-16

我现在正在学习c++ 11中的线程,我遇到了下面的代码行:

lock_guard<mutex> lg(mutex);

不存在变量mutexmutex是唯一的类型名称。

谁能解释一下上面一行代码是如何工作的?

为什么编译器(GCC)不打印任何错误?

完整代码:

#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
using namespace std;
void do_something()
{
    lock_guard<mutex> lg(mutex);
    cout << "Working..." << endl;
    this_thread::sleep_for(chrono::milliseconds(3000));
}
int main()
{
    thread thd(do_something);
    thd.join();
}

编译器认为这是一个原型函数声明:

lock_guard<mutex> lg(mutex);

为了清楚起见,编译器将此解析为一个名为'lg'的函数的声明,该函数以互斥锁作为参数并返回lock_guard实例。

#include <mutex>
int main()
{
    using namespace std;
    lock_guard<mutex> lg(mutex);
    return 0;
}
vc12 output : warning C4930 : 'std::lock_guard<std::mutex> lg(std::mutex)' : prototyped function not called(was a variable definition intended ? )

在c++结构中,类、枚举和联合名称都在它们自己的命名空间中(不是c++ namespace),这允许你使用与结构同名的变量。

例如:

struct SomeStruct
{
    // Member...
};
SomeStruct SomeStruct;  // Valid declaration

至于您没有得到错误,如果您使用的函数在成员函数中显示它,则可能是类具有名称为mutex的成员变量。