为什么在使用try_lock()时需要显式比较?
Why is an explicit comparison needed when using try_lock()?
我正在阅读std::mutex::try_lock
的文档,上面有这个例子:
#include <iostream>
#include <mutex>
int main()
{
std::mutex test;
if (test.try_lock() == true)
std::cout << "lock acquired" << std::endl;
else
std::cout << "lock not acquired" << std::endl;
test.unlock(); // now unlock the mutex
test.lock(); // to lock it again
if (test.try_lock()) // true can be left out
std::cout << "lock acquired" << std::endl;
else
std::cout << "lock not acquired" << std::endl;
test.lock(); // and now the finale (a block)
}
在第二个if语句中,他说true可以省略。为什么第二个是这样,而第一个不是。我检查了,它说try_lock
返回一个布尔值,所以它怎么可能不是真或假,从而使== true
检查多余?
当x
具有类型bool
时,x == true
是愚蠢的。test.try_lock()
返回bool
,因此在两个情况下不需要测试。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 比较两个大小不等的映射c++