<mutex> 如何在没有互斥体实例的情况下lock_guard构造函数进行编译?
How lock_guard<mutex> constructor can be compiled fine without mutex instance?
我现在正在学习c++ 11中的线程,我遇到了下面的代码行:
lock_guard<mutex> lg(mutex);
不存在变量mutex
。mutex
是唯一的类型名称。
谁能解释一下上面一行代码是如何工作的?
为什么编译器(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
的成员变量。
相关文章:
- 在没有太多条件句的情况下,我如何避免被零除
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 在未初始化映射的情况下,将值插入到映射的映射中
- 是默认情况下分配给char数组常量的值
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 如何在不产生任何垃圾的情况下获得C中的像素
- 在已经使用Git的情况下减少编译时间
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 如何在没有信号的情况下从C++执行QML插槽
- 如何在不知道向量大小的情况下输入向量内部的向量?
- 为什么在某些情况下不写入此文件?
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 在没有Xcode的情况下在Mac捆绑包中嵌入框架
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 在C++中如何在没有pow的情况下进行基础计算
- 松弛原子与无同步情况下的记忆连贯性
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 为什么 lock() 在死锁的情况下不抛出异常