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++(中文版)
106
3
目前,本条款的陈述都基于这样的假设,即多个线程会同时调用同一对象的同一个
const
成员函数。如果你撰写的成员函数并不符合这种情况,也就是说,可以保证在同
一对象上不会有多于一个线程来调用它,那么该函数的线程安全性也就可有可无了。
例如,如果类本身就是为独占性的、单线程的用途而设计,则其成员函数是否具备线
程安全性就不甚要紧。在这样的情况下,那些互斥量和
std::atomic
别的对象所带
来的开销都可以避免,同时还可以消除那些包含了它们的类变成只移类这样的副作用。
不过,这些线程无关的场合正在变得越来越罕见,并且会变得更加罕见。可以肯定地说,
const
成员函数都会运行在并发执行的条件下,所以你应该保证
const
成员函数具备
线程安全性。
要点速记
保证
const
成员函数的线程安全性,除非可以确信它们不会用在并发语境中。
运用
std::atomic
型别的变量会比运用互斥量提供更好的性能,但前者仅
适用对单个变量或内存区域的操作。
条款
17
:理解特种成员函数的生成机制
C++
官方用语中,特种成员函数是指那些
C++
会自行生成的成员函数。
C++98
四种特种成员函数:默认构造函数、析构函数、复制构造函数,以及复制赋值运算符。
当然,看文档的时候可别漏了小字部分。这些函数仅在需要时才会生成,亦即,在某
些代码使用了它们,而在类中并未显式声明的场合。仅当一个类没有声明任何构造函
数时,才会生成默认构造函数(只要指定了一个要求传参的构造函数,就会阻止编译
器生成默认构造函数)。生成的特种成员函数都具有 ...
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