Skip to Content
C++语言导学(原书第2版)
book

C++语言导学(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

13.2.1 unique_ptr和shared_ptr

本书到目前为止的例子都是关心定义在作用域内的对象,它们可以在作用域结束的时候释放掉资源,但如果对象是在自由存储上分配的呢?在<memory>当中,标准库提供了两种“智能指针”来管理自由存储上的对象:

·unique_ptr表示唯一所有权。

·shared_ptr表示共享所有权。

这些“智能指针”最基本的作用是防止由于编程疏忽而造成内存泄漏。例如:

在这段代码中,如果i<99或者j<77,则我们“忘了”释放掉指针p。另一方面,unique_ptr确保不论以哪种方式(通过抛出异常,或者通过执行return语句,或者“直达函数末尾”)退出f()都会释放掉它的对象。其实换个角度考虑一下,如果干脆不使用指针也不使用new,就能简单地解决这个问题:

不幸的是,滥用new(以及指针和引用)看起来正在成为一个日益严重的问题。

但是,当你确实需要指针的语义时,那么与内置指针相比,unique_ptr是更好的选择,后者是一种非常轻量级的机制,消耗的时空代价并不比前者大。通过使用unique_ptr,还可以把自由存储上申请的对象传递给函数或者从函数中传出来:

unique_ptr是一个独立的对象(或数组)的句柄,就像vector是对象序列的句柄一样。这二者都以RAII的机制控制其他对象的生命周期,并且都依赖移动语义使得return语句简单高效。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280