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++(中文版)
右值引用
移动语义和完美转发
187
要点速记
如果不使用万能引用和重载的组合,则替代方案包括使用彼此不同的函数
名字、传递
const T&
型别的形参、传值和标签分派。
经由
std::enable_if
对模板施加限制,就可以将万能引用和重载一起使用,
不过这种技术控制了编译器可以调用到接受万能引用的重载版本的条件。
万能引用形参通常在性能方面具备优势,但在易用性方面一般会有劣势。
条款
28
:理解引用折叠
条款
23
曾经提及,实参在传递给函数模板时,推导出来的模板形参会将实参是左值
还是右值的信息编码到结果型别中。但该条款未曾提及,这个编码操作只有在实参被
用以初始化的形参为万能引用时才会发生。不过,有一个充分的理由来解释为什么当
时不提这茬:万能引用是在条款
24
中才介绍。把万能引用和左右值编码信息的论述
综合起来,意思就是,以下面这个模板为例:
template<typename T>
void func(T&& param);
模板形参
T
的推导结果型别中,会把传给
param
的实参
是左值还是右值的信息给编码
进去。
编码机制是直截了当的:如果传递的实参是个左值,
T
的推导结果就是个左值引用型
别;如果传递的实参是个右值,
T
推导结果就是个非引用型别(注意这里的非对称性:
左值的编码结果为左值引用型别,但右值的编码结果却是非引用型别)。是故有下面
的结果:
Widget widgetFactory();
//
返回右值的函数
Widget w;
//
变量(左值)
func(w);
//
调用 ...
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