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++(中文版)
右值引用
移动语义和完美转发
175
条款
27
:熟悉依万能引用型别进行重载的替代方案
条款
26
说过,依万能引用型别进行重载会导致形形色色的问题,独立函数和成员函
数(构造函数尤其问题严重)。不过,该条款也展示多少了这种重载可能有用的若干
用例。这些用例的行为要是能按我们想要的那样运作就好了!本条款进行了一番探索,
目的就在于获得期望的行为,方法是或者通过依万能引用型别进行重载的设计手法,
或者通过限制能匹配的实参型别。
接下来讨论是以条款
26
中构建的代码为基础的,如果你最近没读过该条款,就先复
习一下再往下读。
舍弃重载
条款
26
的第一个例子,
logAndAdd
,可以作为很多函数的代表,这样的函数只需
把本来打算进行重载的版本重新命名成不同的多个名字就可以避免依万能引用型别
进行重载。以
logAndAdd
的两个重载版本为例,就可以分别改成
logAndAddName
logAndAddNameIdx
。啊呀,但这种方法不适用于第二个例子——
Person
类的构造函数,
因为构造函数的名字是由语言固化的。还有,彻底放弃重载也不是长久之计呀!
传递
const T&
型别的形参
一种替代方法是回归
C++98
,使用传递左值常量引用型别来代替传递万能引用型别。
其实,这就是条款
26
做的第一种问题解决尝试。这种方法的缺点是达不到我们想要
的高效率。不过,在已知依万能引用型别进行重载会带来的不良效应以后,放弃部分
效率来保持简洁性不失为仍有一定吸引力的权衡结果。
传值
一种经常能够提升性能,却不用增加一点复杂性的方法,就是把传递的形参从引用型 ...
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