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++(中文版)
60
3
要把那一行伪代码变换成实际代码,有两种方式(有关
std::forward
的信息,参见
条款
25
):
T localObject
(
std::forward<Ts>(params)...
)
;
//
采用小括号
T localObject
{
std::forward<Ts>(params)...
}
;
//
采用大括号
所以,考虑一下对应的调用代码:
std::vector<int> v;
doSomeWork<std::vector<int>>(10, 20);
如果
doSomeWork
在创建
localObject
使用了小括号,结果会得到一个包含
10
个元素
std::vector
。如果
doSomeWork
使用了大括号,结果会得到一个包含
2
个元素的
std::vector
。哪个是对的呢?
doSomeWork
作者不可能下这个判断,只有调用者才
有决定权。
这正是标准库函数
std::make_unique
std::make_shared
(参见条款
21
)所面临的
问题。而这些函数解决问题的办法是在内部使用了小括号,并把这个决定以文档的形
式广而告之,作为其接口的组成部分。
1
要点速记
大括号初始化可以应用的语境最为宽泛,可以阻止隐式窄化型别转换,还
对最令人苦恼之解析语法免疫。
在构造函数重载决议期间,只要有任何可能,大括号初始化物就会与带有
std::initializer_list
型别的形参相匹配,即使其他重载版本有着貌似更
加匹配的形参表。
使用小括号还是大括号,会造成结果大相径庭的一个例子是:使用两个实 ...
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