brenzo
brenzo

Reputation: 769

Is there a cleaner way to define my copy ctor with a mutex?

I have a POD struct like so

struct foo {
  std::mutex m_foo_mutex;
  int a;
  int b;
  int c;
  //......
};

It has more fields than this but the structure should be apparent. The default copy ctor is, of course, ill formed because std::mutex's copy ctor is delete.

It's perfectly fine for my uses to copy this object, and give the copied object a new mutex. So I have defined something like this inside foo.

foo(const foo &foo2) : m_foo_mutex() {
a = foo2.a;
b = foo2.b;
c = foo2.c;
//.......
}

That's all well but it's quite ugly when this struct has 20+ fields, normally the compiler would hide this from me. Is there a cleaner way to express this, or am I stuck with this big ugly constructor?

Upvotes: 0

Views: 129

Answers (1)

Alan Birtles
Alan Birtles

Reputation: 36488

You could wrap just your mutex in a copyable class:

struct CopyableMutex {
    std::mutex mutex;

    CopyableMutex() = default;
    CopyableMutex(const CopyableMutex&) {}
    CopyableMutex& operator= (const CopyableMutex&) {
        return *this;
    }
};

struct foo {
  CopyableMutex m_foo_mutex;
  int a;
  int b;
  int c;
};

You might want to come up with a better name than CopyableMutex though, as obviously it isn't actually copying the mutex!

Upvotes: 4

Related Questions