shared_ptr是c++中的一种常用智能指针,它能够解决C++程序员未及时释放内存空间导致的内存泄露问题。shared_ptr的实现核心是改变其中的引用计数值,下面是我实现的一个简单的shared_ptr,其中主要包括拷贝构造函数、赋值运算符等。
#include <iostream>
using namespace std;
template <typename T>
class myshared_ptr
{
public:
myshared_ptr(T*value) //:ptr(value), count(new int(1))
{
ptr = value;
count = new int(1);
}
myshared_ptr(const myshared_ptr&m)
{
ptr = m.ptr;
count = m.count;
(*count)++;
}
myshared_ptr&operator=(const myshared_ptr&m)
{
if (this != &m)
{
ptr = m.ptr;
count = m.count;
(*count)++;
}
return *this;
}
T&operator->()
{
return this->ptr;
}
~myshared_ptr()
{
(*count)--;
if (*(this->count) == 0)
{
delete ptr;
delete count;