《c++ primer》13.3章节
std::swap()可以对两个同类型的对象进行交换:
struct ceshi
{
explicit constexpr ceshi(int frist,int second)
:frist(frist),second(second)
{
}
int frist;
int second;
};
#define debug qDebug()<<
int main(int argc, char *argv[])
{
ceshi c1(5,6);
ceshi c2(40,50);
debug c1.frist << c1.second;
debug c2.frist << c2.second;
std::swap(c1,c2);
debug c1.frist << c1.second;
debug c2.frist << c2.second;
}
std::swap是通过交换是通过创建一个临时变量赋值实现的。
template<typename _Tp>
inline void swap(_Tp& __a, _Tp& __b)
{
__glibcxx_function_requires(_SGIAssignableConcept<_Tp>)
_Tp __tmp = _GLIBCXX_MOVE(__a);
__a = _GLIBCXX_MOVE(__b);
__b = _GLIBCXX_MOVE(__tmp);
}
对于大的类如果觉得这样效率太低可以自定义类专属的交换函数:
struct ceshi
{
explicit constexpr ceshi(int frist,int second)
:frist(frist),second(second)
{
}
int frist;
int second;
void swap(ceshi & c1,ceshi & c2)
{
qDebug()<<"调用自己的swap()";
std::swap(c1.frist,c2.frist);
std::swap(c1.second,c2.second);
}
};
#define debug qDebug()<<
int main(int argc, char *argv[])
{
ceshi c1(5,6);
ceshi c2(10,20);
debug c1.frist << c1.second;
debug c2.frist << c2.second;
c1.swap(c1,c2);
debug c1.frist << c1.second;
debug c2.frist << c2.second;
}
这里自定义交换函数,自定义只交换对象的成员变量。省去了创建一个大的临时对象的开销。
类的自定义交换函数有个应用场景:在赋值运算符里面使用swap传入一个临时对象。
ceshi& operator=(ceshi other)
{
swap(*this,other);
return *this;
}
当前对象和传入的临时对象交换不会影响原来对象,就有了赋值的效果。