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++(中文版)
94
3
条件的。要调用这样的函数,无须关心程序状态,对于调用方传入的实参也没有限
制。
5
带有宽松契约的函数不可能展现出未定义行为。
而带有宽松契约的函数,就是带有狭隘契约的函数了。对于这些函数,如果前置条件
被违反,则结果成为未定义的。
如果你在撰写的是个带有宽松契约的函数,并且你知道它不会发射异常,那么遵循
本条款的建议,给它加个
noexcept
声明是容易的事。但对于带有狭隘契约的函数
来说,情况就有那么点儿微妙。举例来说,假设你正在撰写一个函数
f
,带有一个
std::string
型别的形参,并假设
f
的自然实现不会产生异常。这就说明
f
应该加上
noexcept
声明。
但再假
f
个前提条件:
std::string
型别的形参不得超过
32
个字符。如果向
f
入一个长度超过
32
std::string
型别对象,则行为未定义,因为按照定义,违反
前置条件就是会导致未定义行为的。
f
并无义务校验这个前置条件,因为函数会断言
其前置条件一定能满足(调用方负责保证断言成立)。即使带有前置条件,
f
加上
noexcept
声明看上去也合情合理:
void f(const std::string& s)
noexcept
;
//
前置条件:
s.length() <= 32
但再假设
f
的实现者选择去校验前置条件违例的情形。这个校验动作并不是必须的,
但也没有禁止,并且校验动作也是有其用途的,例如在做系统测试时就有用。针对被
抛出的异常来做调试,通常比企图跟踪未定义行为的原因要容易。但是,一个前置条
件违例要怎样报告,才能让测试装置或客户方的错误处理程序检测到呢?一个直截了 ...
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
Effective STL

Effective STL

Scott Meyers

Publisher Resources

ISBN: 9787519817749