码迷,mamicode.com
首页 > 其他好文 > 详细

NO.10: 在operator=中处理 "自我赋值"

时间:2017-07-30 22:05:30      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:安全   str   opera   效率   his   swap   argv   std   语句   

1.确保当对象自我赋值时operator=有良好的行为,其中的技术包括 "来源对象" 和 "目标对象" 的地址,精心周到的语句顺序,以及“ copy and swap ” 技术

2.确定任何函数执行操作一个以上对象时,而其中多个对象是同一个对象时,其行为任然正确

 

 

 1 #include <iostream>
 2 
 3 
 4 //1.0
 5 class CopySwap1_0
 6 {
 7 private:
 8     int *value;
 9 public:
10     CopySwap1_0() : value(new int(200))
11     {}
12 
13     ~CopySwap1_0()
14     { delete value; };
15 
16     //不符合 "C++异常安全" 1.没有考虑自赋值情况. 2.new抛出异常的话,原数据销毁
17     CopySwap1_0 &operator=(const CopySwap1_0 &rhs)
18     {
19         delete value;
20         value = new int(*rhs.value);
21         return *this;
22 
23     }
24 
25 };
26 
27 //2.0
28 class CopySwap2_0
29 {
30 private:
31     int *value;
32 public:
33     CopySwap2_0() : value(new int(200))
34     {}
35 
36     ~CopySwap2_0()
37     { delete value; };
38 
39     //保证异常安全,和自赋值情况,但执行效率可以提高
40     CopySwap2_0 &operator=(const CopySwap2_0 &rhs)
41     {
42         if (this == &rhs) return *this;
43 
44         int *temp = value;
45         value = new int(*rhs.value);
46         delete temp;
47         return *this;
48     }
49 
50 };
51 
52 
53 //3.0
54 class CopySwap3_0
55 {
56 private:
57     int *value;
58 public:
59     CopySwap3_0() : value(new int(200))
60     {}
61 
62     ~CopySwap3_0()
63     { delete value; };
64 
65 //    CopySwap3_0 &operator=(const CopySwap3_0 &rhs)
66 //    {
67 //        CopySwap3_0 lhs(rhs);
68 //        std::swap(*this, lhs);
69 //        return *this;
70 //
71 //    }
72 
73 
74     //copy and swap 方式提高执行效率,放弃自赋值检查(因为自赋值出现几率很小,没必要浪费判断效率)
75     //将 "copying执行" 移至函数参数构造阶段,虽然可读性低,但令编译器有时产生更搞笑的代码
76     CopySwap3_0 &operator=(CopySwap3_0 rhs)
77     {
78         std::swap(*this, rhs);
79         return *this;
80 
81     }
82 
83 };
84 
85 
86 int main(int argc, char **argv)
87 {
88     return 0;
89 }

 

NO.10: 在operator=中处理 "自我赋值"

标签:安全   str   opera   效率   his   swap   argv   std   语句   

原文地址:http://www.cnblogs.com/xuaidongstdudyrecording/p/7260431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!