Fix bug in SharedPtr<>::reset() where the pointer wasn't set to NULL when refcount > 1

This commit is contained in:
David Capello 2011-11-13 17:52:26 -03:00
parent 103211509e
commit af26dcaee4
2 changed files with 20 additions and 10 deletions

View File

@ -19,15 +19,11 @@ public:
++m_count; ++m_count;
} }
bool release() void release()
{ {
--m_count; --m_count;
if (m_count == 0) { if (m_count == 0)
delete this; delete this;
return true;
}
else
return false;
} }
long use_count() const long use_count() const
@ -142,6 +138,9 @@ public:
{ {
if (m_ptr != ptr) { if (m_ptr != ptr) {
release(); release();
m_ptr = 0;
m_refCount = 0;
if (ptr) { if (ptr) {
try { try {
m_refCount = new SharedPtrRefCounterImpl<T, DefaultSharedPtrDeleter<T> >(ptr, DefaultSharedPtrDeleter<T>()); m_refCount = new SharedPtrRefCounterImpl<T, DefaultSharedPtrDeleter<T> >(ptr, DefaultSharedPtrDeleter<T>());
@ -161,6 +160,9 @@ public:
{ {
if (m_ptr != ptr) { if (m_ptr != ptr) {
release(); release();
m_ptr = 0;
m_refCount = 0;
if (ptr) { if (ptr) {
try { try {
m_refCount = new SharedPtrRefCounterImpl<T, Deleter>(ptr, deleter); m_refCount = new SharedPtrRefCounterImpl<T, Deleter>(ptr, deleter);
@ -218,10 +220,8 @@ private:
// Removes the reference to the pointee. // Removes the reference to the pointee.
void release() void release()
{ {
if (m_refCount && m_refCount->release()) { if (m_refCount)
m_ptr = 0; m_refCount->release();
m_refCount = 0;
}
} }

View File

@ -129,6 +129,16 @@ TEST(SharedPtr, Compare)
EXPECT_EQ(5, *c); EXPECT_EQ(5, *c);
} }
TEST(SharedPtr, ResetBugDoesntSetPtrToNull)
{
SharedPtr<int> a(new int(5));
{
SharedPtr<int> b(a);
b.reset();
}
EXPECT_EQ(5, *a);
}
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);