C++11:智能指针

文章目录

头文件memory

名称空间 std

what is 智能指针?

诸如 auto_ptr 以及 C++11 新增的 shared_ptr 和 unique_ptr 等智能指针模板使得管理由 new 分配的内存更容易。它们是类。如果使用这些智能指针(而不是常规指针)来保存 new 返回的地址,则不必在以后使用删除运算符。智能指针对象过期时(即超出了类的作用域时),其析构函数将自动调用 delete 运算符,无需手动释放new出来的内存。

四种智能指针

先看下面这段程序:

cpp 复制代码
xxx_ptr<string> pl(new string("auto");
xxx_ptr<string> p2;
p2=p1; 

其中xxx_ptr仅仅是指向string对象的指针。如果不对赋值运算符进行重载,那么在程序结束时释放p1p2一定会异常,因为默认浅拷贝。对于赋值运算符的重载,有以下几种实现办法:

  1. 深拷贝(我们之前自己实现的时候用这个)
  2. 建立所有权概念(auto_ptr, unique_ptr)
  3. 增加指针计数器 (shared_ptr)

使用方法

cpp 复制代码
// 1. 使用构造函数

auto_ptr<string> p1(new string("hahahaha")); 
auto_ptr<string> p2(p_str); //p_str是普通指针
unique_ptr<string> p3(new string("hahahaha")); 
unique_ptr<string> p4(p_str); 
shared_ptr<string> p5(new string("hahahaha")); 
shared_ptr<string> p6(p_str);

//2. 使用make_shared函数

shared_ptr<string> p7 = make_shared<string>("hahahaha")
int tmp = p7.usecount() // 引用次数
auto_ptr

是C++98的方案,现已弃用。

cpp 复制代码
auto_ptr<string> pl(new string("auto");
auto_ptr<string> p2;
p2=p1; //这句话使得p1指向的位置无效,所有权完全给到p2.这句话在编译时不会有任何问题,执行时,再次访问p1内容时却会使程序异常。这是"不安全"的现象,所以弃用
unique_ptr

相比之下,unique_ptr:

cpp 复制代码
unique_ptr<string> pl(new string("auto");
unique_ptr<string> p2;
p2=p1; //编译不通过。被认为是比auto_ptr更"安全"。

那是不是unique_ptr完全不能通过赋值得来呢?如果赋值号右侧的是临时右值的话,是可以的。

cpp 复制代码
unique_ptr<string>demo{const char* s)
{
    unique ptr<string> temp(new string(s));
    return temp;
}
int main()
{ 
    unique_ptr<string> ps;
    ps = demo("Uniquely special");
    return 0;
}

那unique_ptr 如何能够区分安全和不安全的用法呢?答案是它使用了C++11新增的移动构造函数和右值引用。

可以使用new[],而另外两个不能使用new[]

shared_ptr

策略:创建智能更高的指针,跟踪引用特定对象的智能指针数。这称为引用计数(reference counting)。

例如,赋值时,让数将加1,而指针过期时,计数将减1.仅当最后一个指针过期时,才调用delete。

weak_ptr

书上没讲,暂略

相关推荐
BeyondESH33 分钟前
Linux线程同步—竞态条件和互斥锁(C语言)
linux·服务器·c++
豆浩宇43 分钟前
Halcon OCR检测 免训练版
c++·人工智能·opencv·算法·计算机视觉·ocr
WG_171 小时前
C++多态
开发语言·c++·面试
Charles Ray2 小时前
C++学习笔记 —— 内存分配 new
c++·笔记·学习
重生之我在20年代敲代码2 小时前
strncpy函数的使用和模拟实现
c语言·开发语言·c++·经验分享·笔记
迷迭所归处8 小时前
C++ —— 关于vector
开发语言·c++·算法
CV工程师小林9 小时前
【算法】BFS 系列之边权为 1 的最短路问题
数据结构·c++·算法·leetcode·宽度优先
white__ice9 小时前
2024.9.19
c++
天玑y9 小时前
算法设计与分析(背包问题
c++·经验分享·笔记·学习·算法·leetcode·蓝桥杯
姜太公钓鲸23310 小时前
c++ static(详解)
开发语言·c++