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.9.1 指针参数和引用参数

当你希望将一个变量的值改为由函数计算出的结果时,你有三种选择。例如:

你会如何选择呢?我们认为返回值是最明显的方法(因此最不容易出错),例如:

我们倾向于对小对象(例如一个int)使用这种风格。此外,如果一个“大对象”有移动构造函数(见13.3.4节),我们也可以高效地反复拷贝它。

我们如何选择使用引用参数还是指针参数呢?不幸的是,两者都有自己的吸引力和问题,因此没有明确的答案。你需要根据具体函数及其可能的用途来决定。

使用指针参数警告编程者有些东西可能改变。例如:

在incr_p(&x)中需要使用&,这警告用户x可能改变。与之对比,incr_p(x)就是“看起来无辜的”。这导致很多人稍微偏爱使用指针。

另一方面,如果你使用指针作为函数的参数,需要小心某些人可能用空指针(即nullptr)调用函数。例如:

这显然很讨厌。编写incr_p()的人可以防止它:

但是现在incr_p()不像以前看起来那么简单、有吸引力了。第5章讨论如何处理糟糕的参数。与之相比,引用的用户(例如incr_r())有权假设引用的确指向一个对象。 ...

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