@@ -44,9 +44,9 @@ class shared_ptr_base
44
44
{
45
45
private:
46
46
47
- void operator ==(const shared_ptr_base&, const shared_ptr_base& ) const ;
47
+ void operator ==(const shared_ptr_base&) const ;
48
48
49
- void operator !=(const shared_ptr_base&, const shared_ptr_base& ) const ;
49
+ void operator !=(const shared_ptr_base&) const ;
50
50
};
51
51
52
52
@@ -77,27 +77,35 @@ class shared_ptr: private shared_ptr_base
77
77
{
78
78
if (m_pRefCount->Release () == 0 )
79
79
{
80
- delete m_pData;
80
+ if (m_pData)
81
+ delete m_pData;
81
82
delete m_pRefCount;
82
83
}
83
84
}
84
85
85
- shared_ptr<T>& operator =( const shared_ptr<T>& ptr )
86
+ void swap ( shared_ptr<T>& rhs )
86
87
{
87
- if (this != &ptr)
88
- {
89
- if (m_pRefCount->Release () == 0 )
90
- {
91
- delete m_pData;
92
- delete m_pRefCount;
93
- }
94
-
95
- m_pData = ptr.m_pData ;
96
- m_pRefCount = ptr.m_pRefCount ;
97
- m_pRefCount->AddRef ();
98
- }
88
+ T* pData = rhs.m_pData ;
89
+ RefCount* pRefCount = rhs.m_pRefCount ;
90
+ rhs.m_pData = this ->m_pData ;
91
+ rhs.m_pRefCount = this ->m_pRefCount ;
92
+ this ->m_pData = pData;
93
+ this ->m_pRefCount = pRefCount;
99
94
}
100
95
96
+ shared_ptr<T>& operator =(const shared_ptr<T>& rhs)
97
+ {
98
+ /*
99
+ * Copy-and-swap idiom
100
+ * Make a copy of rhs using the copy ctor, swap the values of the copy
101
+ * with this. The destruction of the swapped copy is then taken care of
102
+ * by the destructor
103
+ */
104
+ shared_ptr<T> c (rhs);
105
+ c.swap (*this );
106
+ return *this ;
107
+ }
108
+
101
109
T& operator *()
102
110
{
103
111
return *m_pData;
@@ -114,8 +122,11 @@ class shared_ptr: private shared_ptr_base
114
122
T* m_pData;
115
123
RefCount* m_pRefCount;
116
124
117
- friend bool operator ==(const shared_ptr<T>&, const shared_ptr<T>&);
118
- friend bool operator !=(const shared_ptr<T>&, const shared_ptr<T>&);
125
+ template <class X >
126
+ friend bool operator ==(const shared_ptr<X>&, const shared_ptr<X>&);
127
+
128
+ template <class X >
129
+ friend bool operator !=(const shared_ptr<X>&, const shared_ptr<X>&);
119
130
};
120
131
121
132
0 commit comments