有没有一种更简洁的方法来使用互斥体定义我的复制向量?

问题描述 投票:0回答:1

我有一个像这样的 POD 结构

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

它的字段比这个多,但结构应该很明显。当然,默认的复制因子是错误的,因为

std::mutex
的复制因子是
delete

对于我的用途来说,复制这个对象并为复制的对象提供一个新的互斥体是完全可以的。所以我在里面定义了类似的东西

foo

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

这一切都很好,但是当这个结构体有 20 多个字段时,它就很丑陋了,通常编译器会向我隐藏它。有没有更清晰的方式来表达这一点,或者我是否坚持这个又大又丑的构造函数?

c++ copy-constructor
1个回答
3
投票

您可以将互斥锁包装在可复制的类中:

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;
};

您可能想想出一个比

CopyableMutex
更好的名称,因为显然它实际上并没有复制互斥体!

© www.soinside.com 2019 - 2024. All rights reserved.