C++之智能指针(2)

一、unique_ptr 的使用与实现

前文写到auto_ptr,这个智能指针是c++98出来的,这个指针存在一个隐患就是当进行拷贝后,被拷贝对象管理的资源会被悬空,当使用者不知道情况下可能会对空指针的访问,就会出现问题。为了解决这个问题,unique_ptr出来了,unique_ptr直接禁止拷贝跟赋值操作;

1.1 代码示例:
 #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
struct A
{
public:
	A(int a=0)
		:_a(a)
	{
		cout << "A(int a=0)" << endl;
	}
	~A()
	{
		cout << "delete A" << endl;
	}
private:
	int _a;
};
int main()
{
	unique_ptr<A> unp1(new A(1));
	unique_ptr<A> unp2(new A(2));
	unique_ptr<A> unp3(unp1);//编译报错
	unp2 = unp1;//编译报错
	return 0;
}

它是如何实现的呢?其实很简单,只要禁止使用拷贝构造跟赋值函数就行

1.2实现
//.h文件
#pragma once
namespace ldc
{
	template<class T>
	class unique_ptr
	{
	public:
		unique_ptr(T* ptr)
			:_ptr(ptr)
		{
			cout << "ptr 构造" << endl;
		}
		~unique_ptr()
		{
			cout << "ptr 析构" << endl;//为了方便看它调用的析构
			delete _ptr;
		}
		T& operator*()
		{
			return *_ptr;
		}
		T* operator->()
		{
			return _ptr;
		}
		//禁止调用拷贝构造跟赋值
		unique_ptr(const unique_ptr<T>& unp1) = delete;
		unique_ptr<T>& operator=(const unique_ptr<T>& unp1) = delete;
	
	private:
		T* _ptr;
	};
}
 #define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
using namespace std;
#include "unique_ptr.h"
struct A
{

	A(int a=0)
		:_a(a)
	{
		cout << "A(int a=0)" << endl;
	}
	~A()
	{
		cout << "A 析构 " << endl;
	}
	int _a;
};
int main()
{
	ldc::unique_ptr<A> unp1(new A(1));
	ldc::unique_ptr<A> unp2(new A(2));
	//unique_ptr<A> unp3(unp1);
	//unp2 = unp1;
	cout << ++unp1->_a<< endl;
	cout << ++unp2->_a << endl;
	//ldc::unique_ptr<A> unp3(unp1);
	return 0;
}

运行结果:

当调用拷贝构造时编译会报错:

二、总结

1. unque_ptr的实现其实很简单,就是禁用拷贝跟赋值函数;
2.当某个程序明确不会使用到拷贝功能的时候就可以用unique_ptr;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值