为什么在使用try_lock()时需要显式比较?

Why is an explicit comparison needed when using try_lock()?

本文关键字:比较 try lock 为什么      更新时间:2023-10-16

我正在阅读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,因此在两个情况下不需要测试。