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

4.5.3 避免资源泄漏

有经验的程序员可能已经注意到,我在上面的程序中留下了三个可能导致错误的地方:

·Smiley的实现者可能未能delete指向mouth的指针。

·read_shape()的使用者可能未能delete返回的指针。

·Shape指针容器的拥有者可能未能delete指针所指向的对象。

从这层意义上来看,在自由存储上分配的对象的指针是危险的:我们不应该用一个“普通老式指针”来表示所有权。例如:

除非x是正数,否则这段代码就会发生泄漏。将new的结果赋予一个“裸指针”就是自找麻烦。

这种问题的一个简单解决方案是,如果需要释放资源,则不要使用“裸指针”,而是使用标准库unique_ptr(参见13.2.1节):

这是一个简单、通用且高效的资源管理技术的例子(参见5.3节)。

这一改变有一个令人愉快的副作用,我们不再需要为Smiley定义析构函数。编译器会隐式生成一个析构函数,它会对vector中的unique_ptr(参见5.3节)进行所需的析构操作。使用unique_ptr的代码与正确使用裸指针的代码具有完全相同的效率。 ...

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