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++(中文版)
右值引用
移动语义和完美转发
185
//
复制和移动构造函数等
private:
std::string name;
};
乌拉!美哉!不过,好吧,这句赞美更有可能是那些模板元编程迷发出的,但事实上
这方法不仅能够运作,还表现出了一种独特的从容。这么说的理由,一来是它利用了
完美转发,达成了最高效率,二来它又控制了万能引用和重载的组合,而非简单地禁
用之。该技术可以实施于重载无法避免的场合(如构造函数)。
权衡
本条款关注的头三种技术(舍弃重载、传递
const T&
别的形参和传值)都需要对
待调用的函数形参逐一指定型别,而后两种技术(标签分派和对模板的启用资格施加
限制)则利用了完美转发,因此无须指定形参型别。这个基础决定(指定,还是不指
定型别)不无后果。
按理说,完美转发效率更高,因为它出于和形参声明时的型别严格保持一致的目的,
会避免创建临时对象。在
Person
类的构造函数一例中,完美转发就允许把形如“
Nancy
的字符串字面量转发给某个接受
std::string
的构造函数。而未使用完美转发的技术
则一定得先从字符串字面量出发创建一个临时
std::string
对象,方能满足
Person
的构造函数的形参规格。
但是完美转发亦有不足,首先是针对某些型别无法实施完美转发,尽管它们可以被传
递到接受特定型别的函数,条款
30
探索了这些完美转发的失效案例。
其次是在客户传递了非法形参时,错误信息的可理解性。例如,假设在创建
Person
型别的对象时,传递的是个
char16_t
型别(
C++ ...
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版)

本贾尼 斯特劳斯特鲁普
C++语言导学(原书第2版)

C++语言导学(原书第2版)

本贾尼 斯特劳斯特鲁普
Go语言编程

Go语言编程

威廉·肯尼迪

Publisher Resources

ISBN: 9787519817749