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.4.6 自由空间释放

new运算符会从自由空间中分配(“获取”)内存。由于一台计算机的内存是有限的,因此在使用完毕后将内存归还到自由空间通常是一个好主意。这样自由空间可以将这些内存重新用于新的分配请求。对于大型程序和长时间运行的程序来说,这种自由空间的重用是很重要的。例如:

就像注释中所写的那样,每次调用calc()会导致分配给p的double“泄漏”。例如,调用calc(100,1000)会导致1000个double占用的空间在程序接下来的运行过程中无法使用。

将内存归还自由空间的运算符称为delete。我们对new返回的指针使用delete,令这些内存重新变为自由空间中的可用内存,可供未来分配。现在,这个例子变为:

这个例子还顺带说明了使用自由内存的一个主要原因:我们可以在一个函数中创建对象,并将它们传回调用者。

delete有两种形式:

·delete p释放new分配给单个对象的内存。

·delete[]p释放new分配给对象数组的内存。

虽然有些烦人,但选择正确的形式是程序员的责任。

两次删除一个对象是一个糟糕的错误。例如:

第二个delete p带来两个问题:

·你已不再拥有指针指向的对象,因此自由空间管理器可能已经改变了它的内部数据结构,导致你无法再次正确地执行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