智能指针的简单实现
2016-03-30 18:26
288 查看
智能指针:动态的管理开辟的内存,防止人为的内存泄漏。 SharedPtr的实现: 原理:使用引用计数的原理使多个对象可以指向一块空间。 #define _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; template <class T> 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<T>& operator= ( SharedPtr<T>& 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<int> s(new int(5)); SharedPtr<int> s1(s); SharedPtr<int> s2(s1); SharedPtr<int>s3(new int(7)); SharedPtr<int>s4 = 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 T> class ScopedPtr { public: ScopedPtr(T* ptr) { _ptr = ptr; } ~ScopedPtr() { if (_ptr) { delete _ptr; } } ScopedPtr<T>* operator->() { return _ptr; } ScopedPtr<T>operator*() { return *_ptr; } private: T* _ptr; ScopedPtr<T>& operator=(const ScopedPtr<T>& s); ScopedPtr(const ScopedPtr<T>& s); }; int main() { ScopedPtr<int>s = new int(1); system("pause"); } AutoPtr的实现: 原理:一块空间只能让一个对象指着。 template<class T> class AutoPtr { public: AutoPtr(T* ptr) :_ptr(ptr) {} AutoPtr(AutoPtr<T>& s) { _ptr = s._ptr; s._ptr = NULL; } AutoPtr<T>& operator=(AutoPtr<T>& s) { if (this != &s) { if (_ptr) { delete _ptr; } _ptr = s._ptr; s._ptr = NULL; } } ~AutoPtr() { if (_ptr) { delete _ptr; } } AutoPtr<T> operator*() { return *_str; } AutoPtr<T>& operator->() { return _ptr; } private: T* _ptr; }; int main() { AutoPtr<int> s(new int(2)); AutoPtr<int>s1(s); system("pause"); return 0; }
相关文章推荐
- share_ptr的几个注意点
- Auto Autorun.inf desktop.ini sxs.exe auto.exe类病毒的手动处理完全技巧
- auto病毒引发木马下载者病毒的完美解决方案[原创]
- CSS的inherit与auto使用分析
- How to Auto Include a Javascript File
- Mysql auto_increment 重新计数(让id从1开始)
- 智能指针与弱引用详解
- C++ 智能指针深入解析
- dword ptr指令详细解析
- C++智能指针读书笔记
- C语言关键字auto与register的深入理解
- 在MongoDB中模拟Auto Increment的php代码
- Auto Layout on iOS Versions prior to 6.0 解决办法
- centos下python自动升级到2.7.5
- C++爱好者博客
- C语言中auto,register,static,const,volatile的区别
- How to automatically enroll user and computer certificate in AD
- How to get a boost::shared_ptr from this
- iOS Auto Layout UIView Drawing cycle - stackoverflow
- C++ 智能指针详解