What's a reason to provide a swap() for the user defined type?

十年热恋 提交于 2019-12-08 05:24:37

问题


For example, I have a class which manages a POSIX fd:

class remote_connection:
{
public:
  explicit remote_connection( int socket_fd ) : socket_fd(socket_fd) {}
  ~remote_connection() { close( socket_fd); }

  /* no copy semantic */
  remote_connection( const remote_connection& other ) = delete;
  remote_connection& operator=( const remote_connection& rhs ) = delete;

  remote_connection( remote_connection&& other )
  {
    socket_fd = other.socket_fd;
    other.socket_fd = -1;
  }

  remote_connection& operator=( remote_connection&& rhs )
  {
    close( socket_fd );
    socket_fd = rhs.socket_fd;

    rhs.socket_fd = -1;

    return *this;
  } 

private:
  int socket_fd;
};

And somewhere in code:

/* let '42' and '24' be a valid fds */
remote_connection cl_1( 42 ), cl_2( 24 );

...

using std::swap;

swap( cl_1, cl_2 );

For such an implementation of a remote_connection ADL has found no user defined swap and fall-backs to the std namespace where there's no specialization for the remote_connection, so compiler instantiates a std::swap<remote_connection>() function from a std::swap<T>() template function. That function implementation invokes move ctor and move assignment operator which causes objects to exchange their content.

I could implement a swap() for the remote_connection that would result in the SAME result.

So the question is what can I do so specific within swap for the class that a template std::swap<T>() can't? Or why we should provide an implementation for a type if it can be instantiated by a compiler even for types which manage not trivial sub-objects (POSIX fd, pointers,...)?


回答1:


The global std::swap requires creation of a temporary. A custom class based swap will be aware of the internals of the class, and can do the swap more efficiently, without having to create another variable of the class type.

In your case, that internal swap can just swap the internal socket_id values, without having to do all that extra stuff in the move constructor and move assignment operator (which will be called twice).



来源:https://stackoverflow.com/questions/49959722/whats-a-reason-to-provide-a-swap-for-the-user-defined-type

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