繁体   English   中英

为什么std :: mutex在使用WIndows SOCKET的结构中使用时会创建C2248?

[英]Why does std::mutex create a C2248 when used in a struct with WIndows SOCKET?

我使用结构来支持Windows SOCKET列表:

struct ConnectedSockets{
    std::mutex lock;
    std::list<SOCKET> sockets;
};

当我尝试编译它(Visual Studio 2012)时,我收到以下错误:

“错误C2248: std::mutex::operator =无法访问类'std::mutex'声明的'private'成员”

有人知道如何解决这个问题吗?

std::mutex不可复制,因此您需要自己实现operator= for ConnectedScokets

我假设你想为每个ConnectedSockets实例保留一个mutex ,所以这应该足够了:

ConnectedSockets& operator =( ConnectedSockets const& other )
{
    // keep my own mutex
    sockets = other.sockets; // maybe sync this?

    return *this;
}

根本原因与套接字无关。 std::mutex不可复制,因此编译器无法为ConnectedSockets结构生成默认赋值运算符(即成员)。 您需要指示编译器删除赋值运算符(使用= delete说明符声明它)或手动实现它,例如忽略互斥复制。

// To make ConnectedSockets explicitly non-copyable and get more reasonable
// compiler error in case of misuse
struct ConnectedSockets
{
   std::mutex lock; 
   std::list<SOCKET> sockets;
   ConnectedSockets& operator=(const ConnectedSockets&) = delete;
};

// To make ConnectedSockets copyable but keep mutex member intact
struct ConnectedSockets
{
   std::mutex lock; 
   std::list<SOCKET> sockets;

   ConnectedSockets& operator=(const ConnectedSockets& i_rhs)
   {
      // Need locking? Looks like it can be problem here because
      // mutex:lock() is not const and locking i_rhs wouldn't be so easy
      sockets = i_rhs.sockets;
      return *this;
   }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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