Skip to content

Commit f40ae4e

Browse files
Added copy-and-swap idiom to assignment operator
1 parent 6fe3931 commit f40ae4e

File tree

2 files changed

+29
-18
lines changed

2 files changed

+29
-18
lines changed

src/shared_ptr.hpp

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,9 @@ class shared_ptr_base
4444
{
4545
private:
4646

47-
void operator==(const shared_ptr_base&, const shared_ptr_base&) const;
47+
void operator==(const shared_ptr_base&) const;
4848

49-
void operator!=(const shared_ptr_base&, const shared_ptr_base&) const;
49+
void operator!=(const shared_ptr_base&) const;
5050
};
5151

5252

@@ -77,27 +77,35 @@ class shared_ptr: private shared_ptr_base
7777
{
7878
if(m_pRefCount->Release() == 0)
7979
{
80-
delete m_pData;
80+
if(m_pData)
81+
delete m_pData;
8182
delete m_pRefCount;
8283
}
8384
}
8485

85-
shared_ptr<T>& operator=(const shared_ptr<T>& ptr)
86+
void swap(shared_ptr<T>& rhs)
8687
{
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;
9994
}
10095

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+
101109
T& operator*()
102110
{
103111
return *m_pData;
@@ -114,8 +122,11 @@ class shared_ptr: private shared_ptr_base
114122
T* m_pData;
115123
RefCount* m_pRefCount;
116124

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>&);
119130
};
120131

121132

src/shared_ptr.hpp.gch

1.84 MB
Binary file not shown.

0 commit comments

Comments
 (0)