用c++简单实现智能指针 (二)

2014-11-24 03:09:17 · 作者: · 浏览: 4
: pData(pValue)
{
}
~SP()
{
delete pData;
}

T& operator* ()
{
return *pData;
}

T* operator-> ()
{
return pData;
}
};

void main()
{
SP p(new Person("Scott", 25));
p->Display();
// Dont need to delete Person pointer..
}

template < typename T > class SP
{
private:
T* pData; // Generic pointer to be stored
public:
SP(T* pValue) : pData(pValue)
{
}
~SP()
{
delete pData;
}

T& operator* ()
{
return *pData;
}

T* operator-> ()
{
return pData;
}
};

void main()
{
SP p(new Person("Scott", 25));
p->Display();
// Dont need to delete Person pointer..
}
我们的智能指针这样就真的智能了吗?验证下面的代码:
[cpp]
void main()
{
SP p(new Person("Scott", 25));
p->Display();
{
SP q = p;
q->Display();
// Destructor of Q will be called here..
}
p->Display();
}

void main()
{
SP p(new Person("Scott", 25));
p->Display();
{
SP q = p;
q->Display();
// Destructor of Q will be called here..
}
p->Display();
}
这样就会存在一个问题:p和q关联到了Person类的相同对象指针,当q结束它的作用域时会释放Person类的对象指针,我们用p调用Display()函数会因为垂悬指针而失败。我们应该在不使用它的时候再释放,智能指针中引入计数便可解决。
计数器。
下面实现一个计数器的类RC.
[cpp]
class RC
{
private:
int count; // Reference count

public:
void AddRef()
{
// Increment the reference count
count++;
}

int Release()
{
// Decrement the reference count and
// return the reference count.
return --count;
}
};

class RC
{
private:
int count; // Reference count

public:
void AddRef()
{
// Increment the reference count
count++;
}

int Release()
{
// Decrement the reference count and
// return the reference count.
return --count;
}
};
下面把计数器引入到我们的智能指针中:
[cpp]
template < typename T > class SP
{
private:
T* pData; // pointer
RC* reference; // Reference count

public:
SP() : pData(0), reference(0)
{
// Create a new reference
reference = new RC();
// Increment the reference count
reference->AddRef();
}

SP(T* pValue) : pData(pValue), reference(0)
{
// Create a new reference
reference = new RC();
// Increment the reference count
reference->AddRef();
}

SP(const SP& sp) : pData(sp.pData), reference(sp.reference)
{
// Copy constructor
// Copy the data and reference pointer
// and increment the reference count
reference->AddRef();
}

~SP()
{
// Destructor
// Decrement the reference count
// if reference become zero delete the data
if(reference->Release() == 0)
{
delete pData;
delete reference;
}
}

T& operator* ()
{
return *pData;
}

T* operator-> ()
{
return pData;
}

SP& operator = (const SP& sp)
{
// Assignment operator
if (this != &sp) // Avoid self assignment
{
// Decrement the old reference count
// if reference become zero delete the old data
if(reference->Release() == 0)
{
delete pData;
delete reference;
}

// Copy the data and reference pointer