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版)

5.3 资源管理

通过定义构造函数、拷贝操作、移动操作和析构函数,程序员就能对包含的资源(比如容器中的元素)的生命周期提供完全的控制。而且移动构造函数还允许对象从一个作用域简单高效地移动到另一个作用域。这样,对于我们不能或不希望拷贝出作用域的对象,就可以简单高效地移出作用域。考虑一个表示并发活动的标准库thread(参见15.2节)以及一个含有1000000个double的Vector。对于前者,我们无法拷贝它;对于后者,我们则是不希望拷贝。

在很多情况下,使用Vector和thread这样的资源句柄要优于直接使用内置指针。实际上,标准库“智能指针”(如unique_ptr)本身就是资源句柄(参见13.2.1节)。

我们使用标准库vector存放thread的原因是,在6.2节之前我们还接触不到用一种元素类型参数化Vector的方法。

就像替换掉程序中的new和delete一样,我们也可以将指针转化为资源句柄。在这两种情况下,都将得到更简单也更易维护的代码,而且没什么额外的开销。特别是,我们能实现强资源安全(strong resource safety),换句话说,对于一般概念上的资源,这种方法都可以消除资源泄漏的风险。比如存放内存的vector、存放系统线程的thread和存放文件句柄的fstream。

在很多编程语言中,资源管理任务都主要委托给了垃圾回收器,C++同样提供了一个垃圾回收接口以便程序员插入自己的垃圾回收器。但是,我认为对于资源管理问题垃圾收集是最后的选择,仅当更干净、更通用且局部化更好的替代技术都不可用时才考虑它。我理想中的情况是不制造任何垃圾,从而消除对垃圾回收器的需求:不要产生垃圾! ...

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