PTHREAD_MUTEX_INITIALIZER inside C++ member function cannot compile?

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

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?

回答1:

Instead of this:

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

Try this:

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

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.



回答2:

Use pthread_mutex_init in this case, as the constant is for compile-time initialization.



回答3:

Even if we change this to use an initializer list in the constructor it still fails:

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

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:

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

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:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!