zoukankan      html  css  js  c++  java
  • 【c++】智能指针

    // vc下的智能指针,重点在于拥有权的转移
    
    #include <iostream>
    using namespace std;
    
    template<class Type>
    class Autoptr
    {
    public:
    	Autoptr(int *p = NULL) :ptr(p), owns(ptr != NULL)
    	{}
    	Autoptr(const Autoptr<Type> &t) :ptr(t.release()), owns(t.owns)
    	{}
    	Autoptr<Type>& operator=(const Autoptr<Type> &t)
    	{
    		if (this != &t)// 推断是否给自己赋值
    		{
    			if (ptr != t.ptr)// 推断是否指向同一个空间
    			{
    				if (owns)// 假设有拥有权。则释放当前空间
    				{
    					delete ptr;
    				}
    				else
    				{
    					owns = t.owns;// 反之,得到拥有权
    				}
    				ptr = t.release();// 让t失去拥有权
    			}
    		}
    		return *this;
    	}
    	~Autoptr()
    	{
    		if (owns)
    			delete ptr;
    	}
    public:
    	Type& operator*()const
    	{
    		return (*get());
    	}
    	Type* operator->()const
    	{
    		return get();
    	}
    	Type* get()const
    	{
    		return ptr;
    	}
    	Type* release()const
    	{
    		((Autoptr<Type> *const)this)->owns = false;
    		return ptr;
    	}
    private:
    	bool owns;
    	Type *ptr;
    };
    
    int main()
    {
    	int *p = new int(10);
    	Autoptr<int> pa(p);
    	cout << *pa << endl;
    	Autoptr<int> pa1(pa);
    	cout << *pa1 << endl;
    	int *p1 = new int(100);
    	Autoptr<int> pa2(p1);
    	Autoptr<int> pa3;
    	pa3 = pa2;
    	cout << *pa3 << endl;
    	return 0;
    }
    




  • 相关阅读:
    解决无法连接mysql问题
    nodejs基础(二)
    JS面试题
    node初学者笔记
    nodejs安装、环境配置和测试
    Linux常用命令笔记
    MangoDb的安装及使用
    Redis安装、命令以及设置密码遇到的问题
    测试端口通不通问题
    发布版本Debug和Release的区别
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5136444.html
Copyright © 2011-2022 走看看