C++11智能指针(auto_ptr,unique_ptr,shared_ptr,weak_ptr的详解与模拟实现)
很多小伙伴为了刷题发愁
今天为大家推荐一款刷题神奇哦:刷题面试神器牛客
各大互联网大厂面试真题。从基础到入阶乃至原理刨析类面试题 应有尽有,赶快来装备自己吧!助你面试稳操胜券,solo全场面试官
一:RAII思想的介绍
- 概念:
- RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术。
- 在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。
- 这种做法有两大好处:
- 不需要显式地释放资源。
- 采用这种方式,对象所需的资源在其生命期内始终保持有效。
二:智能指针的原理
-
RAII特性
-
重载operator*和opertaor->,具有像指针一样的行为。
在后续的模拟实现会清楚的看到
三:auto_ptr
-
auto_ptr的实现原理:
管理权转移的思想
// C++库中的智能指针都定义在memory这个头文件中
#include <memory>
class Date
{
public:
Date() { cout << "Date()" << endl;}
~Date(){ cout << "~Date()" << endl;}
int _year;
int _month;
int _day;
};
int main()
{
auto_ptr<Date> ap(new Date);
auto_ptr<Date> copy(ap);
// auto_ptr的问题:当对象拷贝或者赋值后,前面的对象就悬空了
// C++98中设计的auto_ptr问题是非常明显的,所以实际中很多公司明确规定了不能使用auto_ptr
ap->_year = 2018;
return 0;
}
- 通过调试:
我们发现当对象拷贝或者赋值后,前面的对象就悬空了,当运行到
ap->_year = 2018;
时,就发生了空指针的访问,程序报错结束。
anto_ptr模拟实现
template<class T>
class auto_ptr //交换管理权
{
public:
//构造函数
auto_ptr(T* ptr)
:_ptr(ptr)
{}
auto_ptr( auto_ptr& ap)
:_ptr(ap._ptr)
{
ap._ptr = nullptr;
}
T* operator ->()
{
return _ptr;
}
T& operator * ()
{
return *_ptr;
}
~auto_ptr()
{
if (_ptr)
{
delete _ptr;
_ptr = nullptr;
cout << "auto_ptr->析构了" << endl;
}
}
T* _ptr;
};
四: unique_ptr
- C++11中开始提供更靠谱的unique_ptr
int main()
{
unique_ptr<Date> up(new Date);
// unique_ptr的设计思路非常的粗暴-防拷贝,也就是不让拷贝和赋值。
unique_ptr<Date> copy(ap);
return 0;
}
- unique_ptr的实现原理:简单粗暴的防拷贝
unique_ptr 模拟实现
//2.unique_ptr
template<class T>
class unique_ptr //取消赋值和拷贝
{
public:
//构造函数
unique_ptr(T* ptr)
:_ptr(ptr)
{}
unique_ptr(unique_ptr<T>& up) = delete;
unique_ptr<T>& operator = (unique_ptr<T>& up) = delete;
T* operator ->()
{
return _ptr;
}
T& operator * ()
{
return *_ptr;
}
~unique_ptr()
{
if (_ptr)
{
delete _ptr;
_ptr = nullptr;
cout << "unique_ptr->析构了" << endl;
}
}
T* _ptr;
};
五:shared_ptr
C++11中开始提供更靠谱的并且支持拷贝的shared_ptr
int main()
{
// shared_ptr通过引用计数支持智能指针对象的拷贝
shared_ptr<Date> sp(new Date);
shared_ptr<Date> copy(sp);
cout << "ref count:" << sp.use_count() << endl;
cout << "ref count:" << copy.use_count() << endl;
return 0;
}
- hared_ptr的原理:是通过引用计数的方式来实现多个shared_ptr对象之间共享资源。
- 例如:老师晚上在下班之前都会通知,让最后走的学生记得把门锁下。
- shared_ptr在其内部,给每个资源都维护了着一份计数,用来记录该份资源被几个对象共享。
- 在对象被销毁时(也就是析构函数调用),就说明自己不使用该资源了,对象的引用计数减一。**
- 如果引用计数是0**,就说明自己是最后一个使用该资源的对象,必须释放该资源;**
- **如果不是0,就说明除了自己还有其他对象在使用该份资源,**不能释放该资源,否则其他对象就成野指
针了。
shared_ptr 模拟实现
template<class T>
class shared_ptr
{
public:
//构造函数
shared_ptr(T* ptr)
:_ptr(ptr)
, _count (new int(1))
, _pm(new std::mutex)
{}
shared_ptr(shared_ptr<T>& sp)
:_ptr(sp._ptr)
, _count(sp._count)
, _pm(sp._pm)
{
Add_Count();
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
if (_ptr != sp._ptr)
{
Release();
_ptr = sp._ptr;
_count = sp._count;
_pm = sp._pm;
Add_Count();
}
}
//对_count的保护
void Add_Count()
{
_pm->lock();
(*_count)++;
_pm->unlock();
}
void Release()
{
_pm->lock();
bool flag = false;//判断锁是否释放
if (--(*_count) == 0 && _ptr)
{
delete _ptr;
delete _count;
std::cout << "析构了" << std::endl;
flag = true;
}
_pm->unlock();
if (flag)
delete _pm;
}
//指针
T& operator*()
{
return *_ptr;
}
T* operator ->()
{
return _ptr;
}
//析构函数
~shared_ptr()
{
Release();
}
- shared_ptr的线程安全问题 :
- 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时++或–,这
个操作不是原子的,引用计数原来是1,++了两次,可能还是2.这样引用计数就错乱了。会导致资源未
释放或者程序崩溃的问题。所以只能指针中引用计数++、–是需要加锁的,也就是说引用计数的操作是
线程安全的。 - 智能指针管理的对象存放在堆上,两个线程中同时去访问,会导致线程安全问题。
所以我们引入了锁来解决这个问题:
六:weak_ptr
- shared_ptr的循环引用 :
struct ListNode
{
int _data;
shared_ptr<ListNode> _prev;
shared_ptr<ListNode> _next;
~ListNode(){ cout << "~ListNode()" << endl;
};
int main()
{
shared_ptr<ListNode> node1(new ListNode);
shared_ptr<ListNode> node2(new ListNode);
cout << node1.use_count() << endl;
cout << node2.use_count() << endl;
node1->_next = node2;
node2->_prev = node1;
cout << node1.use_count() << endl;
cout << node2.use_count() << endl;
return 0;
}
- 循环引用分析:
- node1和node2两个智能指针对象指向两个节点,引用计数变成1,我们不需要手动delete。
- node1的_next指向node2,node2的_prev指向node1,引用计数变成2。
- node1和node2析构,引用计数减到1,但是_next还指向下一个节点。但是_prev还指向上一个节点。
- 也就是说_next析构了,node2就释放了。
- _ 也就是说_prev析构了,node1就释放了。
- _ 但是_next属于node的成员,node1释放了,_next才会析构,而node1由_prev管理,_prev属于node2
成员,所以这就叫循环引用,谁也不会释放。
-
解决方案:
在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了
// 原理就是,node1->_next = node2;和node2->_prev = node1;时weak_ptr的_next和_prev不会增加
node1和node2的引用计数。
struct ListNode
{
int _data;
weak_ptr<ListNode> _prev;
weak_ptr<ListNode> _next;
~ListNode(){ cout << "~ListNode()" << endl; }
};
int main()
{
shared_ptr<ListNode> node1(new ListNode);
shared_ptr<ListNode> node2(new ListNode);
cout << node1.use_count() << endl;
cout << node2.use_count() << endl;
node1->_next = node2;
node2->_prev = node1;
cout << node1.use_count() << endl;
cout << node2.use_count() << endl;
return 0;
}
七:删除器
如果不是new出来的对象如何通过智能指针管理呢?
其实shared_ptr设计了一个删除器来解决这个问题
// 仿函数的删除器
template<class T>
struct FreeFunc {
void operator()(T* ptr)
{
cout << "free:" << ptr << endl;
free(ptr);
}
};
template<class T>
struct DeleteArrayFunc {
void operator()(T* ptr)
{
cout << "delete[]" << ptr << endl;
delete[] ptr;
}
};
int main()
{
FreeFunc<int> freeFunc;
shared_ptr<int> sp1((int*)malloc(4), freeFunc);
DeleteArrayFunc<int> deleteArrayFunc;
shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);
return 0;
}
八:C++11和boost中智能指针的关系
- C++ 98 中产生了第一个智能指针auto_ptr.
- C++ boost给出了更实用的scoped_ptr和shared_ptr和weak_ptr.
- C++ TR1,引入了shared_ptr等。不过注意的是TR1并不是标准版。
- C++ 11,引入了unique_ptr和shared_ptr和weak_ptr。需要注意的是unique_ptr对应boost的
scoped_ptr。并且这些智能指针的实现原理是参考boost中的实现的。
九:RAII扩展学习
RAII思想除了可以用来设计智能指针,还可以用来设计守卫锁,防止异常安全导致的死锁问题
#include <thread>
#include <mutex>
// C++11的库中也有一个lock_guard,下面的LockGuard造轮子其实就是为了学习他的原理
template<class Mutex>
class LockGuard
{
public:
LockGuard(Mutex& mtx)
:_mutex(mtx)
{
_mutex.lock();
}
~LockGuard()
{
_mutex.unlock();
}
LockGuard(const LockGuard<Mutex>&) = delete;
private:
// 注意这里必须使用引用,否则锁的就不是一个互斥量对象
Mutex& _mutex;
};
mutex mtx;
static int n = 0;
void Func()
{
for (size_t i = 0; i < 1000000; ++i)
{
LockGuard<mutex> lock(mtx);
++n;
}
}
int main()
{
int begin = clock();
thread t1(Func);
thread t2(Func);
t1.join();
t2.join();
int end = clock();
cout << n << endl;
cout <<"cost time:" <<end - begin << endl;
return 0;
}
十:整体代码的展示
#include<iostream>
#include<thread>
#include<mutex>
#include<memory>
using namespace std;
namespace ymh
{
//1.auto_ptr
template<class T>
class auto_ptr //交换管理权
{
public:
//构造函数
auto_ptr(T* ptr)
:_ptr(ptr)
{}
auto_ptr( auto_ptr& ap)
:_ptr(ap._ptr)
{
ap._ptr = nullptr;
}
T* operator ->()
{
return _ptr;
}
T& operator * ()
{
return *_ptr;
}
~auto_ptr()
{
if (_ptr)
{
delete _ptr;
_ptr = nullptr;
cout << "auto_ptr->析构了" << endl;
}
}
T* _ptr;
};
//2.unique_ptr
template<class T>
class unique_ptr //取消赋值和拷贝
{
public:
//构造函数
unique_ptr(T* ptr)
:_ptr(ptr)
{}
unique_ptr(unique_ptr<T>& up) = delete;
unique_ptr<T>& operator = (unique_ptr<T>& up) = delete;
T* operator ->()
{
return _ptr;
}
T& operator * ()
{
return *_ptr;
}
~unique_ptr()
{
if (_ptr)
{
delete _ptr;
_ptr = nullptr;
cout << "unique_ptr->析构了" << endl;
}
}
T* _ptr;
};
template<class T>
class shared_ptr
{
public:
//构造函数
shared_ptr(T* ptr)
:_ptr(ptr)
, _count (new int(1))
, _pm(new std::mutex)
{}
shared_ptr(shared_ptr<T>& sp)
:_ptr(sp._ptr)
, _count(sp._count)
, _pm(sp._pm)
{
Add_Count();
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
if (_ptr != sp._ptr)
{
Release();
_ptr = sp._ptr;
_count = sp._count;
_pm = sp._pm;
Add_Count();
}
}
//对_count的保护
void Add_Count()
{
_pm->lock();
(*_count)++;
_pm->unlock();
}
void Release()
{
_pm->lock();
bool flag = false;//判断锁是否释放
if (--(*_count) == 0 && _ptr)
{
delete _ptr;
delete _count;
std::cout << "析构了" << std::endl;
flag = true;
}
_pm->unlock();
if (flag)
delete _pm;
}
//指针
T& operator*()
{
return *_ptr;
}
T* operator ->()
{
return _ptr;
}
//析构函数
~shared_ptr()
{
Release();
}
public:
T* _ptr;
int* _count;
std::mutex* _pm;
};
}
我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=1iamvly0ep96k