条款11:在operator=中处理“自我赋值”(Handle assignment to self in operator=.)
2010-08-20 11:56
405 查看
1. 证同测试(保证自我复制安全)
传统做法是藉由operator一最前面的一个“证同测试(identity test)达到“自我赋值”的检验目的:
Widget& Widget::operator=(const Widget& rhs)
{
if (this==&rhs) return *this; //证同测试(identity test): 如果是自我赋值,就不做任何事。
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
2. 保证自我复制安全和异常安全的实现
widget& Widget::operator=(const Widget& rhs)
{
Bitmap* pOrig一pb; //记住原先的pb
pb二new Bitmap(*rhs.pb);//令pb指向*pb的一个复件(副本)
delete pOrig;//删除原先的pb
return *this;
}
3. copy and swap技术
class Widget
{
void swap(Widget& rhs);//交换‘this和rhs的数据;详见条款29
};
Widget& Widget::operator=(const Widget& rhs)
{
widget temp(rhs); //为rhs数据制作一份复件(副本)
swap (temp); //将*this数据和上述复件的数据交换。
return *this;
}
4. 总结
1)确保当对象自我赋值时operator=有良好行为。其中技术包括比较“来源对象”和“目标对象”的地址、精心周到的语句顺序、以及copy-and-swap。
2)确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。
传统做法是藉由operator一最前面的一个“证同测试(identity test)达到“自我赋值”的检验目的:
Widget& Widget::operator=(const Widget& rhs)
{
if (this==&rhs) return *this; //证同测试(identity test): 如果是自我赋值,就不做任何事。
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
2. 保证自我复制安全和异常安全的实现
widget& Widget::operator=(const Widget& rhs)
{
Bitmap* pOrig一pb; //记住原先的pb
pb二new Bitmap(*rhs.pb);//令pb指向*pb的一个复件(副本)
delete pOrig;//删除原先的pb
return *this;
}
3. copy and swap技术
class Widget
{
void swap(Widget& rhs);//交换‘this和rhs的数据;详见条款29
};
Widget& Widget::operator=(const Widget& rhs)
{
widget temp(rhs); //为rhs数据制作一份复件(副本)
swap (temp); //将*this数据和上述复件的数据交换。
return *this;
}
4. 总结
1)确保当对象自我赋值时operator=有良好行为。其中技术包括比较“来源对象”和“目标对象”的地址、精心周到的语句顺序、以及copy-and-swap。
2)确定任何函数如果操作一个以上的对象,而其中多个对象是同一个对象时,其行为仍然正确。
相关文章推荐
- effective c++ 条款11 Handle assignment to self in operator=
- 【条款11】Handle assignment to self in operator=
- effective c++ 11: Handle assignment to self in operator =
- Item 11: Handle assignment to self in operator=(Effective C++)
- Effective C++ Item 10,11 Have assignment operators return a reference to *this Handle assignment to self in operator =
- Effective C++ 11. Handle assignment to self in operator=
- [翻译] Effective C++, 3rd Edition, Item 11: 在 operator= 中处理 assignment to self(自赋值)
- Effective C++, 3rd Edition, Item 11: 在 operator= 中处理 assignment to self(自赋值)
- Effective C++——》条款11:在operator=中处理自我赋值
- 【Effective c++】条款11:在operator=中处理“自我赋值”
- Effective C++_笔记_条款11_在operator=中处理“自我赋值”
- 条款11:在operator = 中处理"自我赋值"
- 条款11:在operator=中处理“自我赋值”
- 条款11:在operator=中处理“自我赋值”
- Effective C++ 条款10 令operator=返回一个reference to *this 条款11 在operator=中处理"自我赋值"
- 总结条款:11在operator=中处理“自我赋值”
- Effective C++ -----条款11: 在operator=中处理“自我赋值”
- Item11: Handle assignment to self in operator=
- 条款11:在operator = 中处理“自我赋值”
- 条款11:在operator=中处理“自我赋值”