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++ 中的宏?


- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07