PTHREAD_MUTEX_INITIALIZER inside C ++ member function cannot compile?

class A { public: A(); private: pthread_mutex_t mu; }; A::A() { mu = PTHREAD_MUTEX_INITIALIZER; //cannot compile } 

Can't initialize pthread_mutex_t inside class member function?

+6
source share
3 answers

Instead of this:

 A::A() { mu = PTHREAD_MUTEX_INITIALIZER; //cannot compile } 

Try the following:

 A::A() { pthread_mutex_init( &(mu), NULL); } 

PTHREAD_MUTEX_INITIALIZER is a macro that initializes the C structure for something like {0,0,0,0,0 {0}} and can only be used at the definition point.

+10
source

Use pthread_mutex_init in this case, since the constant is designed to initialize compile time.

+7
source

Even if we change this to use the list of initializers in the constructor, it still doesn't work:

 #include <pthread.h> struct foo { pthread_mutex_t test; foo() : test(PTHREAD_MUTEX_INITIALIZER) {} }; int main() { foo f; } 

We can understand why it fails, and it can only be used for initialization in several contexts by looking at the output from the preliminary process:

 struct foo { pthread_mutex_t test; foo() : test({ { 0, 0, 0, 0, 0, { 0 } } }) {} }; 

You cannot use nested curly braces to initialize as in C ++ 03, but it may be more interesting that C ++ 11 makes this syntax and use completely legal.

In the source code we will see a few more things:

 A::A() { const pthread_mutex_t test = PTHREAD_MUTEX_INITIALIZER; // initialization - fine mu = test; // assignment - fine mu = PTHREAD_MUTEX_INITIALIZER; // assignment - C++11 only } 
+2
source

Source: https://habr.com/ru/post/921382/


All Articles