Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am studying about threads in C++11 now, and I met the following line of code:

lock_guard<mutex> lg(mutex);

There is no variable mutex. mutex is only name of type.

Can anyone explain me how above line of code works?

Why compiler(GCC) doesn't print any error?

Complete code:

#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();
}
like image 917
Dakorn Avatar asked Feb 07 '26 17:02

Dakorn


1 Answers

The compiler thinks this is a prototype function declaration:

lock_guard<mutex> lg(mutex);

To be clear, the compiler parses this as the declaration of a function named 'lg' which takes a mutex as a parameter and returns a lock_guard instance.

#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 ? )
like image 109
Brandon Kohn Avatar answered Feb 09 '26 05:02

Brandon Kohn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!