C++11:逗号运算符的左操作数无效

C++11 : left operand of comma operator has no effect

我在我的项目中开始使用 C++11 后收到此警告

这是给出警告的代码段:

    std::string errortext = "cannot find suitable conversion for %d", index;
    LogToFile(NULL, errortext);
    Assert(false && "cannot find suitable conversion");
    return NULL;

如果我删除 NULL,这段代码还会做同样的事情吗? 或者有什么办法可以解决吗?

#ifndef Assert
    #include <assert.h>
    #define Assert assert
    #define LogToFile (void)(0);
#endif

看起来有些时候,LogToFile 被定义为带参数的宏,而其他时候则没有:

#if 0
#define LogToFile(x, y) some_log_function(x, y, __FILE__, __LINE__, __FUNCTION__)
#else
#define LogToFile (void)(0);
#endif

这会导致扩展如下:

(void)(0);(NULL, errortext);

以及您看到的警告。

很多更好的选择是在两种情况下使用相同数量的参数:

#if 0
#define LogToFile(x,y) some_log_function(x, y, __FILE__, __LINE__, __FUNCTION__)
#else
#define LogToFile(x,y) (void)(y)
#endif

事实上,原始版本被严重破坏,因为它从一个语句变为两个语句,如果它是条件或循环的受控语句,则不会按预期运行。

LogToFile 被定义为 "object-like" 宏(不带参数的宏),而不是类似函数的宏。

给定定义:

#define LogToFile (void)(0);

这一行:

LogToFile(NULL, errortext);

扩展为:

(void)(0); (NULL, errortext);

这是两个独立的陈述。第二个是表达式语句,其中表达式是括号中的逗号表达式(逗号是逗号运算符,而不是参数分隔符)。逗号运算符的左操作数是 NULL.

假设它总是接受两个参数,您可以将定义更改为:

#define LogToFile(arg1, arg2) ((void)(0))

如果它需要可变数量的参数,您可以将其定义为可变参数宏:

#define LogToFile(...) ((void)(0))

(注意:我在定义中添加了额外的括号。)