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++(中文版)
210
6
void doSomeWork()
{
auto pw =
//
创建
Widget
,关于
std::make_unique<Widget>();
// std::make_unique
//
参见条款
21
pw->addFilter();
//
添加使用了
Widget::divisor
的筛选函数
}
// Widget
被销毁,
filters
现在持有空悬指针
当调用
doSomeWork
时创建了一个筛选函数,它依赖于
std::make_unique
创建的
Widget
对象,即,一个含有指向
Widget
指针(
Widget
this
指针的副本)的筛选函
数。该函数被添加到
filters
中,不过当
doSomeWork
执行结束之后,
Widget
对象即被
管理着它的生命期的
std::unique_ptr
毁(参见条款
18
)。从那一刻起,
filters
就含有了一个带有空悬指针的元素。
这一特定问题可以通过将你想捕获的成员变量复制到局部变量中,尔后捕获该局部副
本加以解决:
void Widget::addFilter() const
{
auto divisorCopy = divisor;
//
复制成员变量
filters.emplace_back(
[divisorCopy]
(int value)
//
捕获副本
{ return value % divisorCopy == 0; }
// ...
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