当前位置:网站首页>Tips of this week 141: pay attention to implicit conversion to bool
Tips of this week 141: pay attention to implicit conversion to bool
2022-07-07 17:59:00 【-Flying crane-】
As TotW#141 Originally published in 2018 year 1 month 19 Japan
from Samuel Freilich A literary creation
Two null pointer checks
It is important to check whether the pointer is empty before dereferencing to avoid crashes and errors . This can be done in two ways :
if (foo) {
DoSomething(*foo);
}
if (foo != nullptr) {
DoSomething(*foo);
}
Whereas foo It's a pointer , These two conditions have the same semantics , But the later type check is more strict . stay C++ in , Many types can be implicitly converted to bool, When the pointed type itself is converted to bool Need extra attention when .
Consider the following code , It may have two distinct meanings :
bool* is_migrated = ...;
// This is testing is_migrated Is it empty , Or the real intention is to verify *is_migrated It's true ?
if (is_migrated) {
...
}
This code is clearer :
// It looks like it's for a bool* Null pointer to check
if (is_migrated != nullptr) {
...
}
These two styles are in Google C++ Code is acceptable . So when the underlying type cannot be implicitly converted to bool when , Follow the style of the surrounding code . If the value in question is like std::unique_ptr In this way “ Intelligent pointer ”, Then the semantics and trade-offs are the same .
Optional values and scope distribution
Optional ( for example absl::optional) Is it worth it ? They deserve more careful consideration .
for example :
absl::optional<bool> b = MaybeBool();
if (b) {
... } // When the function returns absl::optional(false) What happened ?
Place the variable declaration in if The scope of the variable will be limited in the condition of the statement , But this value is implicitly converted to a Boolean value , Therefore, it may not be clear which Boolean attribute to test .
The intent of the following code is clearer :
absl::optional<bool> b = MaybeBool();
if (b.has_value()) {
... }
Please note that , actually , The code snippet above is equivalent :absl::optional To bool Only view optional Whether is full , Instead of looking at its contents . Readers may find that optional(false) by true Contrary to common sense , But it's clear optional(false) There is a value . Again , When the underlying type can be implicitly converted to bool when , You need to be extra careful .
One mode of optional return values is to place variable declarations in if In the condition of the statement . This limits the range of variables , But it involves implicit conversion of Booleans :
if (absl::optional<Foo> foo = MaybeFoo()) {
DoSomething(*foo);
}
Be careful : stay C++17 in ,if Statements can contain initializers , Therefore, the scope of the declaration can be limited , While avoiding implicit conversions :
if (absl::optional<Foo> foo = MaybeFoo(); foo.has_value()) {
DoSomething(*foo);
}
Boolean like enumeration
Suppose you have adopted the technique #94 The advice of , And decided to use enumeration instead of bool, In order to get better readability at the calling site . This refactoring may introduce implicit transformations into function definitions :
void ParseCommandLineFlags(
const char* usage, int* argc, char*** argv,
StripFlagsMode strip_flags_mode) {
if (strip_flags_mode) {
// Which value is true ?
...
}
}
You can get extra clarity by replacing implicit conversion with explicit comparison :
void ParseCommandLineFlags(
const char* usage, int* argc, char*** argv,
StripFlagsMode strip_flags_mode) {
if (strip_flags_mode == kPreserveFlags) {
...
}
}
summary
All in all , Pay attention to the transformation from concealment to bool It may not be clear , So consider writing more explicit code :
- Match the pointer type with nullptr Compare ( Especially if the type pointed to can be implicitly converted to bool).
- Use things like absl::optional::has_value() Boolean functions like test whether the container is empty ( Especially if the contained type can be implicitly converted to bool). Yes if Use an optional initialization form to limit the range of variables ( Tips #165). But remember to call only the interface , Don't get value() or has_value() The address of . testing::Optional Matchers can help test .
- Compare an enumeration with a specific value .
Refer to :Contextual conversions
边栏推荐
- Chapter 1 Introduction to CRM core business
- yolo训练过程中批量导入requirments.txt中所需要的包
- Vscode three configuration files about C language
- Cf:c. factors and powers of two [DP + sort + Select Board + select several numbers equal to the minimum number of known sums]
- Functions and usage of tabhost tab
- Understanding of 12 methods of enterprise management
- 数字化转型的主要工作
- 2021-06-28
- 【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
- What is agile testing
猜你喜欢
Toast will display a simple prompt message on the program interface
Functions and usage of viewswitch
Easy to understand [linear regression of machine learning]
Face recognition attendance system based on Baidu flying plasma platform (easydl)
【蓝桥杯集训100题】scratch从小到大排序 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第17题
VSCode关于C语言的3个配置文件
Examen des lois et règlements sur la sécurité de l'information
第2章搭建CRM项目开发环境(搭建开发环境)
MRS离线数据分析:通过Flink作业处理OBS数据
DatePickerDialog and trimepickerdialog
随机推荐
ViewSwitcher的功能和用法
第1章CRM核心业务介绍
做软件测试 掌握哪些技术才能算作 “ 测试高手 ”?
数学分析_笔记_第11章:Fourier级数
[deep learning] 3 minutes introduction
基于RGB图像阈值分割并利用滑动调节阈值
VSCode关于C语言的3个配置文件
机器视觉(1)——概述
Target detection 1 -- actual operation of Yolo data annotation and script for converting XML to TXT file
第2章搭建CRM项目开发环境(数据库设计)
[OKR target management] case analysis
【分布式理论】(一)分布式事务
Audio device strategy audio device output and input selection is based on 7.0 code
开发一个小程序商城需要多少钱?
Native JS verification code
notification是显示在手机状态栏的通知
< code random recording two brushes> linked list
Functions and usage of imageswitch
第3章业务功能开发(实现记住账号密码)
深入浅出【机器学习之线性回归】