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 资源管理

所有重要的程序都包含一项关键任务:管理资源。所谓资源是指程序中符合先申请后释放(显式地或者隐式地)规律的东西,比如内存、锁、套接字、线程句柄和文件句柄等。对于长时间连续运行的程序来说,如果不能及时地释放掉资源(即造成了“泄漏”),就有可能大大降低程序的运行效率甚至造成程序崩溃。即使在短时间运行的程序中,资源泄漏也可能造成严重的后果,比如说由于系统资源短缺导致运行时间增长几个数量级。

标准库组件不会出现资源泄漏的问题,因为它们的设计依赖于支持资源管理的基本语言特性,使用成对的构造函数/析构函数来确保资源不会比其所属对象的生命周期更长。举一个例子,4.2.2节介绍的Vector就是使用构造函数/析构函数对的机制管理元素的,而且所有的标准库容器的实现方式也都与之类似。更重要的,这种方法能与使用异常的错误处理机制正确交互。例如,标准库中的锁类就使用了这种技术:

lck的构造函数首先申请它的mutex,然后thread才开始处理(参见15.5节)。对应的析构函数负责释放掉资源。因此,在本例中,当控制线程离开f()时(通过return语句,或“直到函数末尾”,或抛出异常),scoped_lock的析构函数负责释放掉mutex。

这是“资源请求即初始化”技术(RAII,见4.2.2节)的一个典型应用。RAII是C++中常用的资源处理方法的基础。容器(如vector和map、string和iostream)管理资源(如文件句柄和缓冲区)的方式都十分相似。

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