为什么需要智能指针?
首先,我们来看一个例子。
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
void MemoryLeadTest(){
int* ptr = new int[10];
// 抛异常
vector<int> v(1000000000, 10);
cout << "delete[] ptr;" << endl;
delete[] ptr;
}
int main(){
try{
MemoryLeadTest();
}
catch (const exception& e){
cout << e.what() << endl;
}
system("pause");
return 0;
}
从上述运行结果可以看出,虽然我们写了释放内存的语句,但是由于异常的抛出导致内存释放的语句没有被执行,这种异常安全的问题显然是很严重的。为了解决异常安全的问题,所以就有了智能指针。
什么是智能指针?
要想了解智能指针,我们先来了解一下什么是RAII。
什么是RAII?
RAII(Resource Acquisition Is Initialization,资源获取就是初始化)是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术。
在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,我们实际上把管理一份资源的责任托管给了一个对象。这种做法有两个好处:
- 不需要显式地释放资源。
- 采用这用方式,对象所需的资源在其生命周期内始终保持有效。
下面我们使用RAII的思想来实现一个SmartPtr类,来看一下效果。
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
template<class T>
class SmartPtr{
public:
SmartPtr(T* ptr = nullptr)
: _ptr(ptr)
{}
~SmartPtr(){
if (_ptr){
delete _ptr;
cout << "delete _ptr;" << endl;
}
}
private:
T* _ptr;
};
void MemoryLeadTest(){
int* ptr = new int[10];
// 将ptr指针委托给sp对象
SmartPtr<int> sp(ptr);
vector<int> v(1000000000, 10);
cout << "delete[] ptr;" << endl;
delete[] ptr;
}
int main(){
try{
MemoryLeadTest();
}
catch (const exception& e){
cout << e.what() << endl;
}
system("pause");
return 0;
}
从运行结果可以看出,将动态开辟的内存的指针托管给了对象sp,所以当对象出了作用域之后就会调用其析构函数,析构函数中完成对内存的释放。
智能指针的原理
上述的SmartPtr还不能称之为智能指针,因为它还不具有指针的行为。指针可以解引用,也可以通过->去访问所指空间中的内容,因此:SmartPtr模板类中还得需要将、->重载,才可以使其像指针一样去使用*。
#include <iostream>
#include <stdlib.h>
using namespace std;
template<class T>
class SmartPtr{
public:
SmartPtr(T* ptr = nullptr)
: _ptr(ptr)
{}
~SmartPtr(){
if (_ptr){
delete _ptr;
cout << "delete _ptr;" << endl;
}
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
private:
T* _ptr;
};
struct Date {
int _year;
int _month;
int _day;
};
void smartPtrTest(){
SmartPtr<int> sp1(new int);
*sp1 = 10;
cout << "*sp1: " << *sp1 << endl;
SmartPtr<Date> sp2(new Date);
// 这里应该是sp2.operator->()->_year = 2019
// 为了可读性,编译器省略了一个->
sp2->_year = 2019;
//sp2.operator->()->_month = 1;
sp2->_month = 1;
//sp2.operator->()->_day = 1;
sp2->_day = 1;
}
int main(){
smartPtrTest();
system("pause");
return 0;
}
现在,我们再来总结一下,什么是智能指针?
- 使用RAII特性。
- 重载operator*和operator->,具有像指针一样的行为。
auto_ptr
auto_ptr官方文档
C++98版本的库中就提供了auto_ptr的智能指针。下面我们来看一下auto_ptr。
auto_ptr的使用
#include <iostream>
#include <memory>
#include <stdlib.h>
using namespace std;
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的问题:当对象拷贝或赋值后,前面的对象就被置空了
* 所以这里的ap就是nullptr,对其进行解引用程序崩溃
* C++98中设计的auto_ptr问题是非常明显的,所以实际中严禁使用auto_ptr
*/
ap->_year = 2019;
system("pause");
return 0;
}
auto_ptr的模拟实现
auto_ptr的原理非常简单,就是管理权转移的思想。
#include <iostream>
#include <stdlib.h>
using namespace std;
template<class T>
class AutoPtr{
public:
AutoPtr(T* ptr = nullptr)
: _ptr(ptr)
{}
~AutoPtr(){
if (_ptr){
delete _ptr;
}
}
/*
* 一旦发生拷贝,就将ap中资源转移到当前对象中,然后将ap中指针置空
* 这样就可以解决一份资源被多次释放的问题
*/
AutoPtr(AutoPtr<T>& ap)
: _ptr(ap._ptr)
{
ap._ptr = nullptr;
}
AutoPtr<T>& operator=(AutoPtr<T>& ap){
// 检测是否是自己给自己赋值
if (this != &ap){
//释放当前对象资源
if (_ptr){
delete _ptr;
}
// 管理权转移
_ptr = ap._ptr;
ap._ptr = nullptr;
}
return *this;
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
private:
T* _ptr;
};
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main(){
AutoPtr<Date> ap(new Date);
AutoPtr<Date> copy(ap);
/*
* auto_ptr的问题:当对象拷贝或赋值后,前面的对象就悬空了
* C++98中设计的auto_ptr问题是非常明显的,所以实际中严禁使用auto_ptr
*/
ap->_year = 2019;
system("pause");
return 0;
}
运行结果,程序闪退,由此可见,模拟实现是成功的。
unique_ptr
unique_ptr的使用
#include <iostream>
#include <memory>
#include <stdlib.h>
using namespace std;
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main(){
unique_ptr<Date> up(new Date);
// unique_ptr的设计思路非常的简单粗暴-防拷贝,也就是不允许拷贝和赋值
unique_ptr<Date> copy(up);
system("pause");
return 0;
}
unique_ptr的模拟实现
unique_ptr的实现原理很简单,就是简单粗暴的防拷贝。
#include <iostream>
#include <stdlib.h>
using namespace std;
template<class T>
class UniquePtr{
public:
UniquePtr(T* ptr = nullptr)
: _ptr(ptr)
{}
~UniquePtr(){
if (_ptr){
delete _ptr;
}
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
private:
// C++11实现防拷贝:delete
UniquePtr(const UniquePtr<T>&) = delete;
UniquePtr<T>& operator=(const UniquePtr<T>&) = delete;
// C++98实现防拷贝:只声明不实现 + 声明为私有
UniquePtr(const UniquePtr<T>&);
UniquePtr<T>& operator=(const UniquePtr<T>&);
private:
T* _ptr;
};
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
int main(){
UniquePtr<Date> up(new Date);
UniquePtr<Date> copy(up);
system("pause");
return 0;
}
shared_ptr
shared_ptr官方文档
C++11中提供了更加靠谱的智能指针shared_ptr。
shared_ptr的原理:通过引用计数的方式来实现多个shared_ptr对象之间的资源共享。
- shared_ptr在其内部,给每个资源都维护着一份计数,用来记录该份资源被几个对象共享。
- 在对象被销毁时(也就是析构函数被调用时),就说明自己不使用该资源了,对象的引用计数减一。
- 如果引用计数是0,就说明自己是最后一个使用该资源的对象,必须释放该资源。
- 如果不是0,就说明除了自己外还有其他对象在使用这份资源,不能释放这份资源,否则其他对象就成为野指针了。
shared_ptr的使用
#include <iostream>
#include <memory>
#include <stdlib.h>
using namespace std;
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
void sharedPtrTest(){
shared_ptr<Date> sp(new Date);
cout << "ref count: " << sp.use_count() << endl;
shared_ptr<Date> copy(sp);
cout << "ref count: " << copy.use_count() << endl;
}
int main(){
sharedPtrTest();
system("pause");
return 0;
}
shared_ptr的模拟实现
#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
using namespace std;
template<class T>
class SharedPtr{
public:
SharedPtr(T* ptr = nullptr)
: _ptr(ptr)
, _count(new int(1))
, _mutex(new mutex)
{}
~SharedPtr(){
Release();
}
SharedPtr(const SharedPtr<T>& sp)
: _ptr(sp._ptr)
, _count(sp._count)
, _mutex(sp._mutex)
{
countAdd();
}
SharedPtr<T>& operator=(const SharedPtr<T>& sp){
if (_ptr != sp._ptr){
// 释放旧资源
Release();
// 共享资源
_ptr = sp._ptr;
_count = sp._count;
_mutex = sp._mutex;
// 引用计数加1
countAdd();
}
return *this;
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
int UseCount() const{
return *_count;
}
T* Get(){
return _ptr;
}
private:
void countAdd(){
_mutex->lock();
++(*_count);
_mutex->unlock();
}
void Release(){
bool delete_flag = false;
// 引用计数减1,如果见到0,则释放资源
_mutex->lock();
if (--(*_count) == 0){
delete _ptr;
delete _count;
delete_flag = true;
}
_mutex->unlock();
if (delete_flag){
delete _mutex;
}
}
private:
// 引用计数
int* _count;
// 管理资源的指针
T* _ptr;
// 互斥锁
mutex* _mutex;
};
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year;
int _month;
int _day;
};
void sharedPtrTest(){
SharedPtr<int> sp1(new int(10));
cout << "ref count: " << sp1.UseCount() << endl;
SharedPtr<int> sp2(sp1);
cout << "ref count: " << sp2.UseCount() << endl;
SharedPtr<int> sp3;
cout << "ref count: " << sp3.UseCount() << endl;
}
int main(){
sharedPtrTest();
system("pause");
return 0;
}
shared_ptr的线程安全问题
我们通过一段程序来测试shared_ptr的线程安全问题。需要注意的是shared_ptr的线程安全分为两方面:
- 智能指针对象中引用计数是多个智能指针共享的,两个线程中智能指针的引用计数同时++或–,这个操作不是原子的,引用拘束原来是1,++了两次,可能还是2。这样引用计数就乱了。会导致字眼未释放或者程序崩溃的问题。所以智能指针中引用计数++、–是需要加锁的,也就是说引用计数的操作是线程安全的。
- 智能指针管理的对象存放在堆上,两个线程中同时去访问,会导致线程安全问题。
演示引用计数线程安全问题,将引用计数++、–的锁全部去掉,演示可能不出现线程安全问题,因为线程安全问题是偶发性问题,main函数的n改大一些概率就变大了,比较容易出现线程安全问题。
#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
using namespace std;
template<class T>
class SharedPtr{
public:
SharedPtr(T* ptr = nullptr)
: _ptr(ptr)
, _count(new int(1))
, _mutex(new mutex)
{}
~SharedPtr(){
Release();
}
SharedPtr(const SharedPtr<T>& sp)
: _ptr(sp._ptr)
, _count(sp._count)
, _mutex(sp._mutex)
{
countAdd();
}
SharedPtr<T>& operator=(const SharedPtr<T>& sp){
if (_ptr != sp._ptr){
// 释放旧资源
Release();
// 共享资源
_ptr = sp._ptr;
_count = sp._count;
_mutex = sp._mutex;
// 引用计数加1
countAdd();
}
return *this;
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
int UseCount() const{
return *_count;
}
T* Get(){
return _ptr;
}
private:
void countAdd(){
//_mutex->lock();
++(*_count);
//_mutex->unlock();
}
void Release(){
bool delete_flag = false;
// 引用计数减1,如果见到0,则释放资源
//_mutex->lock();
if (--(*_count) == 0){
delete _ptr;
delete _count;
delete_flag = true;
}
//_mutex->unlock();
if (delete_flag){
delete _mutex;
}
}
private:
// 引用计数
int* _count;
// 管理资源的指针
T* _ptr;
// 互斥锁
mutex* _mutex;
};
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year = 0;
int _month = 0;
int _day = 0;
};
void sharedPtrTest(SharedPtr<Date>& sp, size_t n){
cout << sp.Get() << endl;
for (size_t i = 0; i < n; ++i){
// 这里智能指针拷贝会++计数,智能指针析构会--计数
SharedPtr<Date> copy(sp);
}
}
int main(){
SharedPtr<Date> sp(new Date);
cout << sp.Get() << endl;
const size_t n = 10000;
thread t1(sharedPtrTest, sp, n);
thread t2(sharedPtrTest, sp, n);
t1.join();
t2.join();
system("pause");
return 0;
}
上面是将引用计数的++、–中的加锁解锁操作注释掉了,发现程序会崩溃。
可以看到,资源被释放了两次,导致程序崩溃。
我们再将引用计数++、–的锁加上来看一下运行结果。
#include <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
using namespace std;
template<class T>
class SharedPtr{
public:
SharedPtr(T* ptr = nullptr)
: _ptr(ptr)
, _count(new int(1))
, _mutex(new mutex)
{}
~SharedPtr(){
Release();
}
SharedPtr(const SharedPtr<T>& sp)
: _ptr(sp._ptr)
, _count(sp._count)
, _mutex(sp._mutex)
{
countAdd();
}
SharedPtr<T>& operator=(const SharedPtr<T>& sp){
if (_ptr != sp._ptr){
// 释放旧资源
Release();
// 共享资源
_ptr = sp._ptr;
_count = sp._count;
_mutex = sp._mutex;
// 引用计数加1
countAdd();
}
return *this;
}
T& operator*(){
return *_ptr;
}
T* operator->(){
return _ptr;
}
int UseCount() const{
return *_count;
}
T* Get(){
return _ptr;
}
private:
void countAdd(){
_mutex->lock();
++(*_count);
_mutex->unlock();
}
void Release(){
bool delete_flag = false;
// 引用计数减1,如果见到0,则释放资源
_mutex->lock();
if (--(*_count) == 0){
delete _ptr;
delete _count;
delete_flag = true;
}
_mutex->unlock();
if (delete_flag){
delete _mutex;
}
}
private:
// 引用计数
int* _count;
// 管理资源的指针
T* _ptr;
// 互斥锁
mutex* _mutex;
};
class Date{
public:
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
int _year = 0;
int _month = 0;
int _day = 0;
};
void sharedPtrTest(SharedPtr<Date>& sp, size_t n){
cout << sp.Get() << endl;
for (size_t i = 0; i < n; ++i){
// 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
SharedPtr<Date> copy(sp);
// 这里智能指针访问管理的资源,不是线程安全的。所以我们看看这些值在两个线程中++2n次
// 但是结果不一定是加了2n
++copy->_year;
++copy->_month;
++copy->_day;
}
}
int main(){
SharedPtr<Date> sp(new Date);
cout << sp.Get() << endl;
const size_t n = 10000;
thread t1(sharedPtrTest, sp, n);
thread t2(sharedPtrTest, sp, n);
t1.join();
t2.join();
cout << sp->_year << endl;
cout << sp->_month << endl;
cout << sp->_day << endl;
system("pause");
return 0;
}
从上述结果可以看出,_year、_month、_day并没有被加2n次,这是由于线程不安全导致的。
库中的shared_ptr也是如此,引用计数是线程安全的,但是智能指针访问管理的资源是线程不安全的。
shared_ptr的循环引用
#include <iostream>
#include <stdlib.h>
#include <memory>
using namespace std;
struct Node {
int _data;
shared_ptr<Node> _prev;
shared_ptr<Node> _next;
~Node(){
cout << "~Node()" << endl;
}
};
int main(){
shared_ptr<Node> node1(new Node);
shared_ptr<Node> node2(new Node);
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;
system("pause");
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的引用计数。
#include <iostream>
#include <stdlib.h>
#include <memory>
using namespace std;
struct Node {
int _data;
weak_ptr<Node> _prev;
weak_ptr<Node> _next;
~Node(){
cout << "~Node()" << endl;
}
};
int main(){
shared_ptr<Node> node1(new Node);
shared_ptr<Node> node2(new Node);
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;
system("pause");
return 0;
}
不是new出来的对象如何通过智能指针管理呢?
shared_ptr设计了一个删除器来解决这个问题。
#include <iostream>
#include <stdlib.h>
#include <memory>
using namespace std;
template<class T>
struct FreeFunc{
void operator()(T* ptr){
cout << "free: " << ptr << endl;
free(ptr);
}
};
template<class T>
struct DeleteArrFunc{
void operator()(T* ptr){
cout << "delete[] " << ptr << endl;
delete[] ptr;
}
};
void test(){
FreeFunc<int> ff;
shared_ptr<int> sp1((int*)malloc(4), ff);
DeleteArrFunc<int> daf;
shared_ptr<int> sp2((int*)malloc(4), daf);
}
int main(){
test();
system("pause");
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 <iostream>
#include <stdlib.h>
#include <thread>
#include <mutex>
using namespace std;
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;
system("pause");
return 0;
}