Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a lock_guard on a mutex reference produce C26110

The following code in a Visual Studio Professional 2019 project (version 16.3.6) produces a warning:

#include <thread>
#include <future>

class Foo {
public:
    mutable std::recursive_mutex _writingMutex;
    std::recursive_mutex& writingMutex() const { return _writingMutex; }
};

int main()
{
    Foo a;
    std::lock_guard<std::recursive_mutex> lock(a.writingMutex()); // produces C26110
    std::lock_guard<std::recursive_mutex> lock2(a._writingMutex); // no warning
}

The first lock produces the warning C26110:

Warning C26110 Caller failing to hold lock 'lock' before calling function 'std::lock_guard::~lock_guard'

Why is this so? Does passing the mutex as reference not work?

like image 782
PhilLab Avatar asked Nov 05 '19 11:11

PhilLab


1 Answers

Based on the compilation result of Alan and the comment of rustyx, I will answer my own question:

This is likely to be a code analysis bug in Visual Studio. Looks like C26110 can't recognize a mutex via a reference. The issue was reported here and I added my minimal example as comment there. The issue persists in the most recent version 16.3.7 as well

like image 77
PhilLab Avatar answered Oct 05 '22 21:10

PhilLab