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++(中文版)
202
5
位域
最后一种完美转发失败情形,是位域被用作函数实参。为考察在实践中如何表现,观
察如下这个可以表示
IPv4
头部的模型:
3
struct IPv4Header {
std::uint32_t version:4,
IHL:4,
DSCP:6,
ECN:2,
totalLength:16;
};
如果我们被虐了千百遍的函数
f
(转发函数
fwd
万年不变的目标)的声明式中接受
std::size_t
型别的形参,然后用
IPv4Header
对象的,比如说,
totalLength
字段
调用
f
吧,编译器会乖乖放行:
void f(std::size_t sz);
//
待调用的函数
IPv4Header h;
f
(h.totalLength);
//
没问题
但是,如果是经由
fwd
h.totalLength
转发给
f
就是另一回事了:
fwd
(h.totalLength);
//
错误!
问题在于
fwd
的形参是个引用,而
h.totalLength
是个非
const
的位域。乍听之下,
这也没什么。但是
C++
标准却对于这么个组合以异乎寻常的口吻严加禁止:“非
const
用不得绑定到位域”,该条禁令倒是有极其充分的理由。位域是由机器字的若干任
意部分组成的(例如,
32
int
的第
3
到第
5
个比特),但是这样的实体是不可能有
办法对其直接取址的。我前面曾经提及,在硬件层次,引用和指针本是同一事物。这
么一来,既然没有办法创建指涉到任意比特的指针( ...
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