Reputation: 903
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();
}
Upvotes: 2
Views: 822
Reputation: 1621
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 ? )
Upvotes: 8
Reputation: 409196
In C++ structure, class, enumeration and union names are in their own namespace (not a C++ namespace
), which allows you to have variables with the same name as a structure.
For example:
struct SomeStruct
{
// Member...
};
SomeStruct SomeStruct; // Valid declaration
As for you not getting an error, if the function you use the shown it in a member function, then it could be that the class has a member variable with the name mutex
.
Upvotes: 4