【发布时间】:2018-04-21 19:58:14
【问题描述】:
例如,我有一个管理 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;
};
在代码中的某处:
/* let '42' and '24' be a valid fds */
remote_connection cl_1( 42 ), cl_2( 24 );
...
using std::swap;
swap( cl_1, cl_2 );
对于remote_connection 的这种实现,ADL 发现没有用户定义的swap 并回退到没有专门化remote_connection 的std 命名空间,因此编译器从@ 实例化std::swap<remote_connection>() 函数987654327@模板函数。该函数实现调用移动 ctor 和移动赋值运算符,从而导致对象交换其内容。
我可以为remote_connection 实现swap(),这会产生相同的结果。
所以问题是我可以在swap 中针对template std::swap<T>() 无法做到的课程具体做什么?或者为什么我们应该为一个类型提供一个实现,如果它可以被编译器实例化,即使是管理不平凡的子对象(POSIX fd,指针,...)的类型?
【问题讨论】: