智能指針的簡單實現
智能指針:動態的管理開闢的內存,防止人爲的內存泄漏。
SharedPtr的實現:
原理:使用引用計數的原理使多個對象可以指向一塊空間。
#define _CRT_SECURE_NO_WARNINGS
#include
using namespace std;
template
class SharedPtr
{
public:
SharedPtr()
:_count(new int(1)), _ptr(NULL)
{}
SharedPtr( T* ptr)
:_count(new int(1)), _ptr(ptr)
{}
SharedPtr( SharedPtr& ptr)
:_ptr(ptr._ptr), _count(ptr._count)
{
(*_count)++;
}
SharedPtr& operator= ( SharedPtr& ptr)
{
if (this != &ptr)
{
if (--(*_count) == 0)
{
delete _ptr;
delete _count;
_count = ptr._count;
}
else
{
*_count--;
_count = ptr._count;
}
_ptr = ptr._ptr;
++(*_count);
}
return *this;
}
~SharedPtr()
{
if (*_count == 1)
{
delete _ptr;
delete _count;
}
else
{
(*_count)--;
}
}
T* operator->()
{
return _ptr;
}
T& operator*()
{
return *_ptr;
}
int GetCount()
{
return *_count;
}
void Print()
{
cout << *_count << " " << *_ptr << endl;
}
private:
int* _count;
T* _ptr;
};
void test()
{
SharedPtr s(new int(5));
SharedPtr s1(s);
SharedPtr s2(s1);
SharedPtrs3(new int(7));
SharedPtrs4 = s3;
s4.Print();
s3 = s1;
s4.Print();
s3.Print();
s.Print();
s1.Print();
s2.Print();
}
int main()
{
test();
system("pause");
return 0;
}
ScopedPtr的實現:
ScopedPtr實現原理:防止拷貝構造和賦值運算符的重載。
template
class ScopedPtr
{
public:
ScopedPtr(T* ptr)
{
_ptr = ptr;
}
~ScopedPtr()
{
if (_ptr)
{
delete _ptr;
}
}
ScopedPtr* operator->()
{
return _ptr;
}
ScopedPtroperator*()
{
return *_ptr;
}
private:
T* _ptr;
ScopedPtr& operator=(const ScopedPtr& s);
ScopedPtr(const ScopedPtr& s);
};
int main()
{
ScopedPtrs = new int(1);
system("pause");
}
AutoPtr的實現:
原理:一塊空間只能讓一個對象指着。
template
class AutoPtr
{
public:
AutoPtr(T* ptr)
:_ptr(ptr)
{}
AutoPtr(AutoPtr& s)
{
_ptr = s._ptr;
s._ptr = NULL;
}
AutoPtr& operator=(AutoPtr& s)
{
if (this != &s)
{
if (_ptr)
{
delete _ptr;
}
_ptr = s._ptr;
s._ptr = NULL;
}
}
~AutoPtr()
{
if (_ptr)
{
delete _ptr;
}
}
AutoPtr operator*()
{
return *_str;
}
AutoPtr& operator->()
{
return _ptr;
}
private:
T* _ptr;
};
int main()
{
AutoPtr s(new int(2));
AutoPtrs1(s);
system("pause");
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.