简体   繁体   中英

C++ Initialize struct with mutex field

I'm trying to figure out how to initialize a struct with a mutex field, since the mutex type is not copyable or movable in C++.

I have the struct:

typedef struct sample {
  int field1;
  std::mutex mtx;
} sample_t;

I'm trying to initialize it in the following way, but I keep getting error: use of deleted function. I'm not super familiar with C++ and would love some help!

sample_t* new_sample;
std::mutex a_mtx;
// new_sample->mtx = std::move(a_mtx); (I tried this too)
new_sample->mtx = a_mtx;
new_sample->mtx.lock();
new_sample->field1 = 2;
new_sample->mtx.unlock();

Mutex is not copyable and not moveable. But you don't need either of these operatons, you only need to create sample_t object - std::mutex inside will be initilized by the compiler.

sample_t new_sample;

new_sample.mtx.lock();
new_sample.field1 = 2;
new_sample.mtx.unlock();

Or, if you really need a pointer for some reason:

// sample_t* new_sample = new sample_t;
// you should prefer smart pointers over raw pointers
std::unique_ptr<sample_t> new_sample = std::make_unique<sample_t>();

new_sample->mtx.lock();
new_sample->field1 = 2;
new_sample->mtx.unlock();

As @JarMan pointed out in a comment, in C++ all of a struct's fields are initialized when the struct is created. The error you are getting about "use of deleted function" is telling you that, once the struct exists, you can't just copy over the mutex which is already there.

However, you do need to actually create the struct; the code you have makes a pointer but doesn't create the struct itself. So you probably want:

sample_t* new_sample = new sample_t;
new_sample->mtx.lock();
// ... etc

Also, note, in C++ you don't have to do the typedef when declaring structs; you can just do

struct sample_t {
  int field1;
  std::mutex mtx;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM