1. Exchange assignment of class objects
Hasptr.h
class Hasptr
{
public:
Hasptr(const std::string &s = std::string()):
ps(new std::string(s),
i(0),
use(new std::size_t(1))) {
}
Hasptr(const Hasptr &p):ps(p.ps),i(p.i),use(p.use){
++*use};
Hasptr& operator=(const Hasptr&);
~Hasptr();
private:
std::string *ps;
int i;
std::size_t *use;
}
The exchange code is:
Hasptr temp = v1; //创建v1的一个临时副本
v1 = v2; //将v2赋值给v1
v2 =temp; //将保存v1的值赋予v2
2. Optimization
In the above exchange process, one copy and two assignments are required. The memory allocation of string brings overhead. I prefer swap to exchange pointers instead of allocating new copies of string:
string &temp = v1.ps;
v1.ps = v2.ps;
v2.ps = temp.ps;
2. 1 You can customize a version of swap on the class. When exchanging two HasPtr objects, you only need to exchange their internal pointers:
class HasPtr{
friend void swap(HasPtr &lhs,HasPtr &rhs);
}
inline swap(HasPtr&,HasPtr&)
{
using std::swap;
swap(lhs.ps,rhs.ps); //交换指针,而不是string的数据
swap(lhs.i;rhs.i); //交换int成员
}
2. 2 Use swap in assignment operator
Using copy and exchange technology, this technology exchanges a copy of the operand on the left with a copy of the operand on the right.
rhs is passed by value:
HasPtr& HasPtr::operator=(HasPtr rhs)
{
//交换左侧运算对象和局部变量rhs的内容
swap(*this,rhs);
return *this; //rhs 被销毁,从而delete了rhs中的指针
}
- Note: The assignment operator is exceptionally safe and can handle self-assignment correctly.
[Reference]
[1] Code referenceCountSwap.h