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.5 空指针

如果你没有其他指针用来初始化一个指针,那么使用空指针nullptr:

当0值被赋给一个指针时,它被称为空指针(null pointer)。我们经常通过检测指针是否为nullptr来检查一个指针是否有效(它是否指向什么东西)。例如:

这并不是一个完美的检测,因为p0可能包含一个碰巧不是0的“随机”值(例如我们忘记了初始化),或者一个已经被删除对象的地址(见12.4.6节)。但是,一般来说这已是我们所能做得最好的。我们实际上不必明确提及nullptr,因为if语句会检测它的条件是否为nullptr:

考虑到它更直接地表达了“p0有效”的思想,我们更喜欢这种简短的形式,但是也有不同意见。

如果我们有一个指针有时指向一个对象,而有时什么都不指向,我们就需要使用空指针。这种情况很少见,比很多人想象的更少。思考一下:如果你没有对象需用一个指针指向,那你又为什么定义那个指针呢?你不能等到有一个对象时再做吗?

用名字nullptr表示空指针是C++11的新特性,因此在旧代码中,人们通常使用0(零)或NULL代替nullptr。两种旧的替代方法都会导致混淆和/或错误,因此优先选择更专用的nullptr。 ...

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