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

8.5.4 传常量引用

当传递占用存储空间小的值,如一个整数、一个双精度数或者一个单词(6.3.2节)时,传值方式简单、直接、高效。但对于占用存储空间大的值,如一个图像(通常有几百万位大小)、一个大表(比如说几千个整数)或一个长字符串(比如说几百个字符)时,又如何呢?这种情况下,拷贝的代价就会非常高。我们不必为拷贝代价所困扰,但做不必要的工作就可能会很麻烦了,这意味着我们不能直接表达我们想要什么。例如,我们可能会编写下面这个函数来打印一个浮点数vector:

这个print()函数适用于所有规模的vector,例如:

这段代码可以得到我们想要的结果,但首次调用print()需要拷贝10个双精度数(大概80个字节),第二次调用需要拷贝一百万个双精度数(大概8兆字节),而第三次调用需要拷贝多少字节我们不知道。在此,我们必须问自己一个问题:“为什么我们要拷贝全部数据?”我们只不过是想打印vector,而不是拷贝它们的元素。显然,必须要有一种方法,能使我们向函数传递一个变量,而不拷贝其值。一个类似的例子是,如果你被分派了一个任务——为图书馆中的书籍建一个目录,馆长不会给你送去图书馆大楼和其内所有内容的一份拷贝,而只是把图书馆的地址发送给你,这样你就能到图书馆去浏览馆藏书籍。因此,我们需要某种方法,能将要打印的vector的“地址”而不是其拷贝传送给print()函数。这样的“地址”被称为引用(reference),其使用方法如下: ...

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