什么是双重评估,为什么应避免? [英] What is double evaluation and why should it be avoided?

查看:171
本文介绍了什么是双重评估,为什么应避免?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中使用诸如此类的宏

I was reading that in C++ using macros like

#define max(a,b) (a > b ? a : b)

可能会导致双重评估".有人可以给我举一个例子,说明何时发生双重评估以及为什么它不好吗?

can result in a 'double evaluation'. Can someone give me an example of when a double evaluation occurs and why it's bad?

PS:令人惊讶的是,除了 Clojure (其中的一个示例)外,我在进行谷歌搜索时找不到任何详细的解释.我不明白).

P.S.: Surprisingly I couldn't find any detailed explanation when googling for it except for an example in Clojure (which I can't understand).

推荐答案

想象一下您是这样写的:

Imagine you wrote this:

#define Max(a,b) (a < b ? b : a)

int x(){ turnLeft();   return 0; }
int y(){ turnRight();  return 1; }

然后这样称呼它:

auto var = Max(x(), y());

您知道turnRight()将执行两次吗?该宏Max将扩展为:

Do you know that turnRight() will be executed twice? That macro, Max will expand to:

auto var = (x() < y() ? y() : x());

在评估条件x() < y()之后,程序将在y() : x()之间进行所需的分支:在我们的情况下为true,第二次调用y().观看 在Coliru上直播 .

After evaluating the condition x() < y(), the program then takes the required branch between y() : x(): in our case true, which calls y() for the second time. See it Live On Coliru.

简单地说,将表达式作为参数传递给预处理器 处理.

Simply put, passing an expression as an argument to your function-like macro, Max will potentially evaluate that expression twice, because the expression will be repeated where ever the macro parameter it takes on, is used in the macro's definition. Remember, macros are handled by the preprocessor.

因此,最重要的是,不要仅仅因为您希望它是泛型的而使用宏定义函数(在这种情况下实际上是表达式),而可以使用函数有效地完成定义模板

So, bottom line is, do not use macros to define a function (actually an expression in this case) simply because you want it to be generic, while it can be effectively done using a function templates

PS:C ++具有 std::max 模板函数.

PS: C++ has a std::max template function.

这篇关于什么是双重评估,为什么应避免?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆