Skip to Content
C++程序设计:原理与实践(基础篇)(原书第2版)
book

C++程序设计:原理与实践(基础篇)(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
9h 36m
Chinese
Pearson
Content preview from C++程序设计:原理与实践(基础篇)(原书第2版)

12.5.2 析构函数和自由空间

析构函数概念上很简单,但它是大多数最有效的C++编程技术的基础。基本思想是:

·无论一个类对象需要使用哪些资源,这些资源都要在构造函数中获取。

·在对象的生命周期中,它可以释放资源并获得新的资源。

·在对象的生命周期结束后,析构函数释放对象拥有的所有资源。

在vector中用一对构造函数、析构函数处理自由空间内存就是这一思想的一个典型例子。我们将在14.5节中提供这种思想的更多例子。本节将考察一个重要的应用,它结合使用了自由空间和类层次。考虑下面代码:

这段代码看起来很合理,事实也的确如此,它运行一切正常。不过让我们分析一下它是如何做到的,这段代码揭示了一些精巧、重要和简单的技术。在函数fct()中,Text(见18.11节)对象tt在离开函数时被正确销毁。Text有一个string成员,很明显需要调用它的析构函数——string像vector一样处理内存的获取和释放。对于tt,正确销毁是很容易的;编译器只需像12.5.1节中描述的那样调用Text的生成析构函数即可。但是,从fct()返回的Text对象会怎样?调用者f()完全不了解q指向一个Text,它所知道的是q指向一个Shape。delete q如何调用Text的析构函数?

在19.2.1节中,我们快速地介绍了Shape的析构函数。实际上,Shape的析构函数是virtual的,这就是问题的关键。当我们使用delete q时,delete会查看q的类型,以确定是否需要调用析构函数,如果需要的话就调用它。因此,delete ...

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

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

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

本贾尼 斯特劳斯特鲁普
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano

Publisher Resources

ISBN: 9787111562252