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++(中文版)
右值引用
移动语义和完美转发
203
to-const
)。在按值传递的形参这种情况下,被调用的函数显然收到是位域内的值的副本;
而在常量引用形形参这种情况下,标准要求这时引用实际绑定到存储在某种标准整型
(例如
int
)中的位域值的副本。常量引用不可能绑定到位域,它们绑定到的是“常规”
对象,其中复制了位域的值。
这么一来,把位域传递给完美转发函数的关键,就是利用转发目的函数接收的总是位
域值的副本这一事实。你可以自己制作一个副本,并以该副本调用转发函数。例如,
IPv4Header
一例中,下述代码即演示了该技巧:
//
复制位域值,初始化形式参见
条款
6
auto length = static_cast<std::uint16_t>(h.totalLength);
fwd(length);
//
转发该副本
结语
在绝大多数情形下,完美转发就如规定所言的方式运作如仪。你很少需要特别留意什
么。但当它无法运作时,亦即,当一些看上去合理的代码编译失败,或者更讨厌的情况,
可以通过编译,行为却表现得和预料不同,重要的是要了解完美转发的不完美之所在,
同样重要的是知道如何规避它们。在绝大多数情形下,这些规避手法都是直截了当的。
要点速记
完美转发的失败情形,是源于模板型别推导失败,或推导结果是错误的型别。
会导致完美转发失败的实参种类有大括号初始化物、以值
0
NULL
表达的
空指针、仅有声明的整型
static const
成员变量、模板或重载的函数名字,
以及位域。
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