Copy-and-swap
来源:互联网 发布:java final成员变量 编辑:程序博客网 时间:2024/05/01 19:18
为了在自定义类里重载一个异常安全(exception safe)的赋值操作符,创造了一个这样的习惯用语。也叫:Create-Temporary-and-Swap。
要想写健壮的C++代码,异常安全非常重要。
可以给异常安全分三级:
1> 基本安全:实现简单、代价小。应该作为常规手段。
2> 很安全:在任何场合都实现这一步不太可能。本例的赋值操作符重载算是一个。
3> 不抛出异常:可以看non-throwing swap。
所谓“Create-Temporary-and-Swap”,就是先申请新资源,用后再释放。
1> 在申请新资源的时候,要使用RAII原则。
2> 申请成功之后,使用non-throwing swap原则交换资源。
[cpp] view plaincopy
- class String {
- char * str;
- public:
- String& operator = (String const &s)
- {
- String temp (s); // copy-constructor -- RAII
- temp.swap (*this); // non-throwing swap
- return *this;
- }
- void swap (String &s) throw ()
- {
- std::swap(this->str, s.str);
- }
- };
有时会加入对参数的判断:
[cpp] view plaincopy
- class String {
- char * str;
- public:
- String& operator = (String const &s)
- {
- if (this != &s)
- String(s).swap (*this); // copy-constructor and non-throwing swap
- return *this;
- }
- void swap (String &s) throw ()
- {
- std::swap(this->str, s.str);
- }
- };
在函数内部的临时变量,其实可以省略,只要用传值的方式:
[cpp] view plaincopy
- String& operator = (String s) // pass-by-value
- {
- s.swap (*this); // Non-throwing swap
- return *this;
- }
这种作法在某些情况下可以得到优化。
如果s绑定到lvalue,无优化,栈内会有临时对象被创建;如果绑定到rvalue,一般就会省略掉copy ctor的调用。
[cpp] view plaincopy
- String createString(); // a function that returns a String object.
- String s;
- s = createString(); // 这是rvalue的一例。使用传值的赋值操作符,可得到优化
在C++0x标准中,这样的赋值操作符叫做“统一赋值操作符”,因为它合“拷贝赋值”、“移动赋值”为一体了。C++0x编译器一旦发现某个类有move ctor存在,总会对临时的rvalue进行优化的。
老编译器当然没有move ctor,但是能对赋值操作进行rvalue的优化,也算是有的一比。
0 0
- copy and swap
- Copy-and-swap
- copy and swap
- Copy-and-swap
- C++使用技巧:copy and swap idiom
- C++中的copy-and-swap idiom
- What is the copy-and-swap idiom?
- What is the copy-and-swap idiom?
- copy-and-swap改进"异常安全"
- effective C++之copy and swap
- C++的 copy-and-swap idiom 是什么
- Copy-and-swap idiom详解和实现安全自我赋值
- copy and swap技巧与移动赋值操作符
- Copy-and-swap idiom详解和实现安全自我赋值
- C++ copy and swap (拷贝交换技术)
- The Rule of Big Three and half: Copy-and-swap Idiom
- copy,copy_backward,swap,transform
- 【C++深入探索】Copy-and-swap idiom详解和实现安全自我赋值
- hdu-2509 Be the Winner
- Windows 上同时使用Python2.x 与 3.x
- EM算法
- /proc文件系统
- 如何成为坐拥百万的WEB开发者
- Copy-and-swap
- Virtualbox虚拟Ubuntu共享文件夹设置
- 谈谈防 SQL 注入式攻击策略
- 工具类commons-io的文件监控
- POJ1546 Basically Speaking
- Could not open ServletContext resource [/WEB-INF/applicationContext.xml]解决方法
- VIM 学习
- hdu-1944&& 1534 S-Nim
- 类与类之间的几种关系(继承、实现、依赖、关联、聚合、组合)