本文介绍了当获取max var时,使用函数和宏之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读combase.cpp代码,找到以下内容:

reading combase.cpp code, I find following:

/* We have to ensure that we DON'T use a max macro, since these will typically   */
/* lead to one of the parameters being evaluated twice.  Since we are worried    */
/* about concurrency, we can't afford to access the m_cRef twice since we can't  */
/* afford to run the risk that its value having changed between accesses.        */

    template<class T> inline static T ourmax( const T & a, const T & b )
    {
        return a > b ? a : b;
    }



我不明白为什么max macro导致一个参数评估两次?

I don't understand why "max macro leads to one of the parameters being evaluated twice"?

推荐答案

请考虑

Consider an usage like in this code sample:

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

int main()
{

  int a = 0;
  int b = 1;

  int c = max(a++, b++);

  cout << a << endl << b << endl;
  return 0;

}

打算打印 1 2 ,但宏扩展为:

The intention probably was to print 1 and 2, but macro expands to:

int c = a++ > b++ ? a++ : b++;

b 1 3

因此,

在某些情况下,作为参数传递给宏的表达式可以被多次计算。

Hence,
In some cases, expressions passed as arguments to macros can be evaluated more than once.

这篇关于当获取max var时,使用函数和宏之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 00:07