Skip to Content
Effective Modern C++(中文版)
book

Effective Modern C++(中文版)

by Scott Meyers
April 2018
Intermediate to advanced
303 pages
4h 54m
Chinese
China Electric Power Press Ltd.
Content preview from Effective Modern C++(中文版)
34
1
C++11
中,知道了这个,其实也就是满足一下猎奇心理而已,但如果和
C++14
decltype(auto)
的支持这么联合一下,一个看似无关紧要的返回值写法上的小改动,
就会影响到函数的型别推导结果:
decltype(auto)
f1()
{
int x = 0;
return x
;
// decltype(x)
int
,所以
f1
返回的是
int
}
decltype(auto)
f2()
{
int x = 0;
return (x)
;
// decltype((x))
int&
,所以
f2
返回的是
int&
}
请注意,问题不仅仅在于
f2
f1
有着返回值型别的不同,更重要的是
f2
回了一个
局部变量的引用!这种代码会把你送上未定义行为的快车——你永远不想乘坐的那种
列车。
主要的教训在于,使用
decltype(auto)
时需要极其小心翼翼。看似是用以推导型别
表达式的写法这样无关紧要的细节,却影响着
decltype(auto)
得出的结果。为了保
证推导所得的型别和你期望的一致,请使用条款
4
讲述的技术。
同时,请勿因此丢掉了大局观。没错,
decltype
(无论是单独使用,还是和
auto
配合
使用)时不时地会得出意外的型别推导结果,但那说到底并非正常情形。在正常情形下,
decltype
产生的
型别就和你期望的一致。
以上的说法在
decltype
应用于名字时尤其成立,因为在那种情况下,
decltype
的行
为可谓名副其实:它得出的就是该名字的声明型别(
declared type
)。
要点速记 ...
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

流畅的Python(第2版)

流畅的Python(第2版)

Luciano Ramalho
Go语言编程

Go语言编程

威廉·肯尼迪

Publisher Resources

ISBN: 9787519817749