一、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;
}
运行结果:
当调用拷贝构造时编译会报错: