zoukankan      html  css  js  c++  java
  • 【C++】模拟实现auto_ptr

      看了《Effctive C++》,里面提到用对象去管理资源,可以有效防止内存泄漏.

      结合auto_ptr特性,稍微思考了一下,实现了一个简单的auto_ptr

      (因为代码量小,就不分文件了)

    #define _CRT_SECURE_NO_WARNINGS
    #include<iostream>
    using namespace std;
    template<typename T>
    class AutoPtr{
    public:
    	//构造函数
    	AutoPtr(T *ptr = NULL)
    		:_ptr(ptr){}
    	//拷贝构造函数
    	AutoPtr(AutoPtr & p)
    		:_ptr(p._ptr){
    		p._ptr = NULL;
    	}
    	//赋值运算符重载
    	AutoPtr &operator=(AutoPtr &p){
    		//判断自我赋值
    		if (_ptr != p._ptr){
    			//
    			if (_ptr != NULL){
    				delete _ptr;
    				_ptr = NULL;
    			}
    			_ptr = p._ptr;
    			p._ptr = NULL;
    		}
    		return *this;
    	}
    	//对*重载
    	T& operator*(){
    		return *_ptr;
    	}
    	//对->重载
    	T* operator->(){
    		return _ptr;
    	}
    	//析构函数
    	~AutoPtr(){
    		if (_ptr != NULL){
    			delete _ptr;
    			_ptr = NULL;
    		}
    	}
    private:
    	T *_ptr;
    };
    //测试函数
    void FunTest(){
    	int *p = new int(5);
    	AutoPtr<int> ap1(p);
    	AutoPtr<int> ap2(ap1);
    	AutoPtr<int> ap3;
    	ap3 = ap2;
    	p = new int(10);
    	AutoPtr<int> ap4(p);
    	ap4 = ap3;
    }
    int main(){
    	FunTest();
    	return 0;
    }
    

      所以这个auto_ptr感觉还有挺坑的,只能有一个对象掌握资源,如果想用多个对象管理同一资源的话....考虑使用share_ptr.

  • 相关阅读:
    Ajax 导出Excel 方式
    配置文件类型
    Ionic 发布Release 版本
    $cordovaNetwork 使用
    Web Api 跨域问题
    Python学习(五)--字典
    Python学习(四)--字符串
    Python学习(三)--列表和元组
    mac下安装HTMLTestRunner
    mac下selenium+python环境搭建
  • 原文地址:https://www.cnblogs.com/qq329914874/p/6075505.html
Copyright © 2011-2022 走看看