5

我正在使用一个结构来支持 Windows SOCKET 的列表:

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

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

“错误 C2248:std::mutex::operator =无法访问在类中声明的‘私有’成员'std::mutex'

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

4

2 回答 2

6

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

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

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

    return *this;
}
于 2013-01-10T17:37:45.810 回答
2

根本原因与套接字无关。std::mutex不可复制,因此编译器无法为ConnectedSocketsstruct 生成默认赋值运算符(它是成员)。您需要指示编译器删除赋值运算符(使用= 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;
   }
};
于 2013-01-10T17:44:44.227 回答