class A {
public:
A();
private:
pthread_mutex_t mu;
};
A::A()
{
mu = PTHREAD_MUTEX_INITIALIZER; //cannot compile
}
Can't I initialize pthread_mutex_t
inside a class member function?
class A {
public:
A();
private:
pthread_mutex_t mu;
};
A::A()
{
mu = PTHREAD_MUTEX_INITIALIZER; //cannot compile
}
Can't I initialize pthread_mutex_t
inside a class member function?
Instead of this:
Try this:
The PTHREAD_MUTEX_INITIALIZER is a macro,a C struct initializer for something like {0,0,0,0,0{0}} and can only be used at the point of definition.
Even if we change this to use an initializer list in the constructor it still fails:
We can see why it fails and an only be used for initialisation in a few contexts by looking at the output from the pre-processsor:
It's not legal to use nested braces for initialisation like that in C++03, but what's more interesting perhaps is that C++11 makes this syntax and usage perfectly legal.
In your original code we can see a few more things:
Use
pthread_mutex_init
in this case, as the constant is for compile-time initialization.