第一步:针对单独类型的模板

为了完成智能指针首先第一步的想法。

class shape_wrapper {
public:
explicit shape_wrapper(
shape* ptr = nullptr)
: ptr_(ptr) {}
~shape_wrapper()
{
delete ptr_;
}
shape* get() const { return ptr_; } private:
shape* ptr_;
};

这个类可以完成智能指针的最基本的功能:对超出作用域的对象进行释放。

但是

1.这个类只适用于 shape 类

2.该类对象的行为不够像指针

3.拷贝该类对象会引发程序行为异常

要让这个类能够包装任意类型的指针,我们需要把它变成一个类模板

第二步:变成类模板

template <typename T>
class smart_ptr {
public:
explicit smart_ptr(T* ptr = nullptr)
: ptr_(ptr) {}
~smart_ptr()
{
delete ptr_;
}
T* get() const { return ptr_; }
private:
T* ptr_;
};

解决像不像指针的问题:

它不能用 * 运算符解引用

它不能用 -> 运算符指向对象成员

它不能像指针一样用在布尔表达式里

template <typename T>
class smart_ptr {
public:

T& operator*() const { return *ptr_; }
T* operator->() const { return ptr_; }
operator bool() const { return ptr_; }
}

第三步:拷贝构造和赋值

第一种粗鲁的方式

解决了会对同一内存释放两次,通常情况下会导致程序崩溃的问题。

template <typename T>
class smart_ptr {

smart_ptr(const smart_ptr&)
= delete;
smart_ptr& operator=(const smart_ptr&)
= delete;

};

第二种移动所有权

大致实现如下

template <typename T>
class smart_ptr {

smart_ptr(smart_ptr& other)
{
ptr_ = other.release();
}
smart_ptr& operator=(smart_ptr& rhs)
{
smart_ptr(rhs).swap(*this);
return *this;
}

T* release()
{
T* ptr = ptr_;
ptr_ = nullptr;
return ptr;
}
void swap(smart_ptr& rhs)
{
using std::swap;
swap(ptr_, rhs.ptr_);
}

};

在拷贝构造函数中,通过调用 other 的 release 方法来释放它对指针的所有权。在赋值函数中,则通过拷贝构造产生一个临时对象并调用 swap 来交换对指针的所有权。实现上是不复杂的。

如果你学到的赋值函数还有一个类似于 if (this != &rhs) 的判断的话,那种用法更啰嗦,而且异常安全性不够好——如果在赋值过程中发生异常的话,this 对象的内容可能已经被部分破坏了,对象不再处于一个完整的状态。

上面代码里的这种惯用法则保证了强异常安全性:赋值分为拷贝构造和交换两步,异常只可能在第一步发生;而第一步如果发生异常的话,this 对象完全不受任何影响。无论拷贝构造成功与否,结果只有赋值成功和赋值没有效果两种状态,而不会发生因为赋值破坏了当前对象这种场景。

还是不够完善,没有支持移动语义,于是继续进行修改如下

template <typename T>
class smart_ptr {

smart_ptr(smart_ptr&& other)
{
ptr_ = other.release();
}
smart_ptr& operator=(smart_ptr rhs)
{
rhs.swap(*this);
return *this;
}

};

修改的地方:

1.把拷贝构造函数中的参数类型 smart_ptr& 改成了 smart_ptr&&;现在它成了移动构造函数。

2.把赋值函数中的参数类型 smart_ptr& 改成了 smart_ptr,在构造参数时直接生成新的智能指针,从而不再需要在函数体中构造临时对象。现在赋值函数的行为是移动还是拷贝,完全依赖于构造参数时走的是移动构造还是拷贝构造。

根据 C++ 的规则,如果我提供了移动构造函数而没有手动提供拷贝构造函数,那后者自动被禁用

到这里我们完成了一个C++11 的 unique_ptr 的基本行为。

第四步:unique_ptr的完善:子类指针向基类指针的转换

直接上代码,利用内置类型自己的判断来辅助完成转换

  template <typename U>
smart_ptr(smart_ptr<U>&& other)
{
ptr_ = other.release();
}

到这里我们完成了一个完整的unique_ptr的转换

第五步:unique_ptr转变为shared_ptr

多个不同的 shared_ptr 不仅可以共享一个对象,在共享同一对象时也需要同时共享同一个计数。当最后一个指向对象(和共享计数)的 shared_ptr 析构时,它需要删除对象和共享计数。我们下面就来实现一下

我们先来写出共享计数的接口:

class shared_count {
public:
shared_count();
void add_count();
long reduce_count();
long get_count() const;
};
class shared_count {
public:
shared_count() : count_(1) {}
void add_count()
{
++count_;
}
long reduce_count()
{
return --count_;
}
long get_count() const
{
return count_;
} private:
long count_;
};

大体框架:构造函数、析构函数和私有成员变量

template <typename T>
class smart_ptr {
public:
explicit smart_ptr(T* ptr = nullptr)
: ptr_(ptr)
{
if (ptr) {
shared_count_ =
new shared_count();
}
}
~smart_ptr()
{
if (ptr_ &&
!shared_count_
->reduce_count()) {
delete ptr_;
delete shared_count_;
}
} private:
T* ptr_;
shared_count* shared_count_;
};

构造函数跟之前的主要不同点是会构造一个 shared_count 出来。析构函数在看到 ptr_ 非空时(此时根据代码逻辑,shared_count 也必然非空),需要对引用数减一,并在引用数降到零时彻底删除对象和共享计数。原理就是这样,不复杂。

当然,我们还有些细节要处理。为了方便实现赋值(及其他一些惯用法),我们需要一个新的 swap 成员函数:

  void swap(smart_ptr& rhs)
{
using std::swap;
swap(ptr_, rhs.ptr_);
swap(shared_count_,
rhs.shared_count_);
}

赋值函数可以跟前面一样,保持不变,但拷贝构造和移动构造函数是需要更新一下的:

  smart_ptr(const smart_ptr& other)
{
ptr_ = other.ptr_;
if (ptr_) {
other.shared_count_
->add_count();
shared_count_ =
other.shared_count_;
}
}
template <typename U>
smart_ptr(const smart_ptr<U>& other)
{
ptr_ = other.ptr_;
if (ptr_) {
other.shared_count_
->add_count();
shared_count_ =
other.shared_count_;
}
}
template <typename U>
smart_ptr(smart_ptr<U>&& other)
{
ptr_ = other.ptr_;
if (ptr_) {
shared_count_ =
other.shared_count_;
other.ptr_ = nullptr;
}
}

除复制指针之外,对于拷贝构造的情况,我们需要在指针非空时把引用数加一,并复制共享计数的指针。对于移动构造的情况,我们不需要调整引用数,直接把 other.ptr_ 置为空,认为 other 不再指向该共享对象即可。

不过,上面的代码有个问题:它不能正确编译。编译器会报错,像:

fatal error: ‘ptr_’ is a private member of ‘smart_ptr<circle>’

错误原因是模板的各个实例间并不天然就有 friend 关系,因而不能互访私有成员 ptr_ 和 shared_count_。我们需要在 smart_ptr 的定义中显式声明:

  template <typename U>
friend class smart_ptr;

第六步:指针类型转换

对应于 C++ 里的不同的类型强制转换:我们能不能让我们的智能指针同样支持这种转换?

static_cast   reinterpret_cast    const_cast   dynamic_cast

智能指针需要实现类似的函数模板。实现本身并不复杂,但为了实现这些转换,我们需要添加构造函数,允许在对智能指针内部的指针对象赋值时,使用一个现有的智能指针的共享计数。如下所示:

我们希望它达成的效果是:

template <typename T, typename U>
smart_ptr<T> dynamic_pointer_cast(
const smart_ptr<U>& other)
{
T* ptr =             //取出具体的指针
dynamic_cast<T*>(other.get());
return smart_ptr<T>(other, ptr);    //再根据具体的指针来构造目标,借助构造函数来完成
}

补充一个构造函数

  template <typename U>
smart_ptr(const smart_ptr<U>& other,
T* ptr)
{
ptr_ = ptr;
if (ptr_) {
other.shared_count_
->add_count();
shared_count_ =
other.shared_count_;
}
}

总结代码

#include <utility>  // std::swap

class shared_count {  // 引用计数类
public:
shared_count() noexcept
: count_(1) {}
void add_count() noexcept
{
++count_;
}
long reduce_count() noexcept
{
return --count_;
}
long get_count() const noexcept
{
return count_;
} private:
long count_;
}; template <typename T> // 有计数功能的智能指针
class smart_ptr {
public:
template <typename U>
friend class smart_ptr;//模板类自身friend explicit smart_ptr(T* ptr = nullptr)
: ptr_(ptr)
{
if (ptr) {      // 如果指针为空,则不创建计数类
shared_count_ =
new shared_count();
}
}
~smart_ptr()
{
if (ptr_ &&
!shared_count_
->reduce_count()) {
delete ptr_;
delete shared_count_;
}
} smart_ptr(const smart_ptr& other)        // 相同指针类的拷贝赋值
{
ptr_ = other.ptr_;
if (ptr_) {
other.shared_count_
->add_count();
shared_count_ =
other.shared_count_;
}
}
template <typename U>
smart_ptr(const smart_ptr<U>& other) noexcept // 不同指针类的拷贝赋值
{
ptr_ = other.ptr_;
if (ptr_) {
other.shared_count_->add_count();
shared_count_ = other.shared_count_;
}
}
template <typename U>
smart_ptr(smart_ptr<U>&& other) noexcept   // 移动赋值函数
{
ptr_ = other.ptr_;
if (ptr_) {
shared_count_ =
other.shared_count_;
other.ptr_ = nullptr;// 设置为nullptr
}
}
template <typename U>
smart_ptr(const smart_ptr<U>& other,      // 构造函数,经过验证可以动态转换之后的调用
T* ptr) noexcept
{
ptr_ = ptr;
if (ptr_) {
other.shared_count_
->add_count();
shared_count_ =
other.shared_count_;
}
}
smart_ptr&
operator=(smart_ptr rhs) noexcept
{
rhs.swap(*this);
return *this;
} T* get() const noexcept
{
return ptr_;
}
long use_count() const noexcept
{
if (ptr_) {
return shared_count_
->get_count();
} else {
return 0;
}
}
void swap(smart_ptr& rhs) noexcept    // 通过成员函数swap内部调用 std内部的标准swap
{
using std::swap;
swap(ptr_, rhs.ptr_);
swap(shared_count_,
rhs.shared_count_);
} T& operator*() const noexcept
{
return *ptr_;
}
T* operator->() const noexcept
{
return ptr_;
}
operator bool() const noexcept
{
return ptr_;
} private:
T* ptr_;
shared_count* shared_count_;
}; template <typename T>
void swap(smart_ptr<T>& lhs,          // 对对象方法进行封装
smart_ptr<T>& rhs) noexcept
{
lhs.swap(rhs);
} template <typename T, typename U>
smart_ptr<T> static_pointer_cast(
const smart_ptr<U>& other) noexcept
{
T* ptr = static_cast<T*>(other.get());    // 进行检验之后会调用构造函数
return smart_ptr<T>(other, ptr);
} template <typename T, typename U>
smart_ptr<T> reinterpret_pointer_cast(
const smart_ptr<U>& other) noexcept
{
T* ptr = reinterpret_cast<T*>(other.get());
return smart_ptr<T>(other, ptr);
} template <typename T, typename U>
smart_ptr<T> const_pointer_cast(
const smart_ptr<U>& other) noexcept
{
T* ptr = const_cast<T*>(other.get());
return smart_ptr<T>(other, ptr);
} template <typename T, typename U>
smart_ptr<T> dynamic_pointer_cast(
const smart_ptr<U>& other) noexcept
{
T* ptr = dynamic_cast<T*>(other.get());
return smart_ptr<T>(other, ptr);
}

如果你足够细心的话,你会发现我在代码里加了不少 noexcept。这对这个智能指针在它的目标场景能正确使用是十分必要的。我们会在下面的几讲里回到这个话题。

02 | 自己动手,实现C++的智能指针的更多相关文章

  1. 自己动手实现智能指针auto_ptr

    面试的时候,我们经常会被问到如何自己动手实现智能指针auto_ptr.今天我就一边参考STL库中的源代码,一边将auto_ptr的实现敲一遍. auto_ptr归根到底是一个模版类,那么这个类要实现哪 ...

  2. stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结

    stl中auto_ptr,unique_ptr,shared_ptr,weak_ptr四种智能指针使用总结 1. auto_ptrauto_ptr主要是用来解决资源自动释放的问题,比如如下代码:voi ...

  3. C++ 智能指针 shared_ptr

    今天晚上去旁听了C++高级编程的课,其中提到智能指针.第一反映还以为是auto_ptr呢,一听才知道是share_ptr这个.哦,原来是C++11特性.大致的原因是auto_ptr有一点缺陷,而sha ...

  4. ATL和vc++中的智能指针(分别是CComPtr和_com_ptr_t)

    一.智能指针的概念 智能指针是一个类,不是指针,智能指针在所包含的指针不再被使用时候会自动释放该所包含指针所占用的系统资源,而不用手动释放. 原理:智能指针封装了包含指针的AddRef()函数和Rel ...

  5. 智能指针之 weak_ptr

    1. weak_ptr 介绍 std::weak_ptr 是一种智能指针,它对被 std::shared_ptr 管理的对象存在非拥有性("弱")引用.在访问所引用的对象指针前必须 ...

  6. ndk学习之c++语言基础复习----C++线程与智能指针

    线程 线程,有时被称为轻量进程,是程序执行的最小单元. C++11线程: 我们知道平常谈C++线程相关的东东基本都是基于之后要学习的posix相关的,其实在C++11有自己新式创建线程的方法,所以先来 ...

  7. cc40a_demo_Cpp_智能指针c++_txwtech

    //40_21days_Cpp_智能指针c++_cc40a_demo.cpp_txwtech //智能指针.auto_ptr类//*常规指针-容易产生内存泄漏,内存被占满,程序就死机,或者系统死机// ...

  8. enote笔记法使用范例(2)——指针(1)智能指针

    要知道什么是智能指针,首先了解什么称为 “资源分配即初始化” what RAII:RAII—Resource Acquisition Is Initialization,即“资源分配即初始化” 在&l ...

  9. C++11 shared_ptr 智能指针 的使用,避免内存泄露

    多线程程序经常会遇到在某个线程A创建了一个对象,这个对象需要在线程B使用, 在没有shared_ptr时,因为线程A,B结束时间不确定,即在A或B线程先释放这个对象都有可能造成另一个线程崩溃, 所以为 ...

随机推荐

  1. LGP2414题解

    难不成是我后缀自动机学魔怔了,AC 自动机都能套上线段树 题意:给你一颗 Trie,每次询问两个节点 \(u,v\),\(u\) 代表的字符串在 \(v\) 代表的字符串中出现了多少次. 让我们思考一 ...

  2. mac电脑sublime text3安装pretty json插件

    因http://packagecontrol.io/地址被墙无法实现自动安装,导致sublime Text3安装插件非常麻烦,总是出现There Are No Packages Available F ...

  3. 远程控制Windows2003下安装Pcanywhere导致Awgina.dll出错的解决办法

    远程控制的时候出现的问题引用 症状启动计算机时,"欢迎使用 Windows"登录屏幕不出现.您还可能会看到与下面的某条信息类似的错误信息: ? 一个最近安装的程序使欢迎屏幕和快速用 ...

  4. C++设计模式 - 迭代器模式(Iterator)

    数据结构模式 常常有一-些组件在内部具有特定的数据结构,如果让客户程序依赖这些特定的数据结构,将极大地破坏组件的复用.这时候,将这些特定数据结构封装在内部,在外部提供统一的接口,来实现与特定数据结构无 ...

  5. ORM,Django对数据库的连接和使用

    ORM,Django对数据库连接和使用数据 ORM(对象关系映射) 很多语言中的web框架都有这个概念 为什么要有ORM? 写程序离不开数据 新的语法,不需要我们自己写SQL语句 我们按照新的语法写代 ...

  6. select 中的timeout

    1. select 相关man 资料 /* According to POSIX.1-2001 */ #include <sys/select.h> /* According to ear ...

  7. 组合(n选k问题)

    #include "iostream.h" #include "string.h" int a[100]; void dfs(int n,int k) { if ...

  8. SpringBoot starter 作用在什么地方?

    依赖管理是所有项目中至关重要的一部分.当一个项目变得相当复杂,管理依赖会成为一个噩梦,因为当中涉及太多 artifacts 了. 这时候 SpringBoot starter 就派上用处了.每一个 s ...

  9. Kafka 分区的目的?

    分区对于 Kafka 集群的好处是:实现负载均衡.分区对于消费者来说,可以提高并发度,提高效率.

  10. MySQL 有关权限的表都有哪几个?

    MySQL 服务器通过权限表来控制用户对数据库的访问,权限表存放在 MySQL 数 据库里,由 MySQL_install_db 脚本初始化.这些权限表分别 user,db,table_priv,co ...