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

无人久伴 提交于 2019-12-04 08:29:13

A std::mutex is not copyable, so you will need to implement the operator= for ConnectedScokets yourself.

I presume you want to keep a mutex per instance of ConnectedSockets, so this should be enough:

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

    return *this;
}

Root cause has nothing about sockets. std::mutex is not copyable, so compiler fails to generate default assignment operator (which is memberwise) for ConnectedSockets struct. You need to instruct compiler to delete assignment operator (declare it using = delete specifier) or implement it manually, e.g. ignoring mutex copying.

// 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;
   }
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!