Why should I avoid macros in C++?(为什么我应该避免 C++ 中的宏?)
问题描述
我读过很多书&我应该避免在 C++ 中使用宏的教程.很好,但为什么呢?我不明白.它们非常有用,经常在 C 语言中使用.
I have read in many books & tutorials that I should avoid macros in c++. Fine, but why? I don't get it. They are very useful and often used in C.
有人可以(非常)详细地解释一下,为什么我应该在 C++ 中避免使用它们?
Could someone explain (very) detailed, why I should avoid them in C++?
推荐答案
宏不尊重范围规则,而是在文本级别操作,而不是在语法级别.由此产生了许多可能导致奇怪的、难以隔离的错误的陷阱.
Macros don't respect scoping rules and operate at the textual level, as opposed to the syntax level. From this arise a number of pitfalls that can lead to strange, difficult to isolate bugs.
考虑以下众所周知的例子:
Consider the following well-known example:
#define max(a, b) ((a) < (b) ? (b) : (a))
⋮
int i = max(i++, j++);
在这种情况下,首选的替代方法是函数模板:
The preferred alternative in this case is a function template:
template <typename T>
T max(const T & a, const T & b) { return a < b ? b : a; }
这是另一个导致微妙问题的案例:
Here's another case that leads to subtle problems:
#define CHECK_ERROR(ret, msg)
if (ret != STATUS_OK) {
fprintf(stderr, "Error %d: %s
", ret, msg);
exit(1);
}
⋮
if (ready)
CHECK_ERROR(try_send(packet), "Failed to send");
else
enqueue(packet);
你可能认为解决方法很简单,就是把 CHECK_ERROR
的内容包裹在 { … }
中,但是由于 ; 导致编译不了.
在 else
之前.
You might think that the solution is as simple as wrapping the contents of CHECK_ERROR
in { … }
, but this won't compile due to the ;
before the else
.
为了避免上述问题(else
附加到 CHECK_ERROR
的 if
而不是外部 if
),应该将这样的宏包装在 do ... while (false)
中,如下所示:
To avoid the above problem (the else
attaching to CHECK_ERROR
's if
instead of the outer if
), one should wrap such macros in do … while (false)
as follows:
#define CHECK_ERROR(ret, msg)
do {
if (ret != STATUS_OK) {
fprintf(stderr, "Error %d: %s
", ret, msg);
exit(1);
}
while (false)
这对宏的含义没有影响,但确保整个块始终被视为单个语句,并且不会以令人惊讶的方式与 if
语句交互.
This has no effect on the meaning of the macro, but ensures that the entire block is always treated as a single statement and doesn't interact in surprising ways with if
statements.
长话短说,宏在许多层面都是危险的,因此只能作为最后的手段使用.
Long story short, macros are hazardous at many levels and should thus be used only as a last resort.
这篇关于为什么我应该避免 C++ 中的宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我应该避免 C++ 中的宏?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01