c++ - 获取最大变量时,使用函数和宏有什么区别

标签 c++

<分区>

阅读 combase.cpp 代码,我发现以下内容:

/* 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;       
    } 

我不明白为什么“最大宏会导致其中一个参数被计算两次”?

最佳答案

考虑像这样的用法 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;

}

本意可能是打印 12,但宏扩展为:

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

b 递增两次,程序打印 13

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

关于c++ - 获取最大变量时,使用函数和宏有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10695945/

相关文章:

c++ - 使用多维 std::initializer_list

c++ - pragma omp parallel for 与 pragma omp parallel

c++ - 为什么我的 C++ 代码出现 "undeclared identifier"错误?

c++ - cpp程序中system函数的使用

c++ - 使用输入文件并将其传递给函数

c++ - 在不同的 Visual Studio 平台上运行时间不同?

c++ - 将 MFC 库复制到项目

c++ - 在 C++ 中检查字符串中的非拉丁符号

c++ - 在 C++ 中使用 <<++ 和 >>++ 运算符

c++ - 对象的性能影响