2017-09-28 42 views
1

PVS Studio抱怨危險的表情。參數「MSG」必須由括號上下面的代碼C++代碼包圍PVS Studio抱怨危險的宏觀表達

#include <iostream> 

#define X ("X") 
#define Y ("Y") 
#define Z ("Z") 

#define FRED(msg) msg << Z  // <<-- Warning from PVS Studio 
#define WILMA(msg) X << FRED(msg) 
#define BUDDY(msg) Y << FRED(msg) 
int main() 
{ 
    std::cout << WILMA(BUDDY("xxxxxx")) << std::endl; 
    return 0; 
} 

從PVS Studio中的警告消息是

V1003 The macro 'FRED' is a dangerous expression. The parameter 'msg' must be surrounded by parentheses. sample_demo.cpp 7 

在從該工具的建議和添加括號: 的#include

#define X ("X") 
#define Y ("Y") 
#define Z ("Z") 

#define FRED(msg) (msg) << Z 
#define WILMA(msg) X << FRED(msg) 
#define BUDDY(msg) Y << FRED(msg) 
int main() 
{ 
    std::cout << WILMA(BUDDY("xxxxxx")) << std::endl; 
    return 0; 
} 

這種變化似乎產生無效代碼。從VS2017編譯器錯誤如下:

error C2296: '<<': illegal, left operand has type 'const char [2]' 
error C2297 : '<<' : illegal, right operand has type 'const char [7]' 

問題

我敢肯定從PVS Studio中的建議是不是在這種特殊情況下是正確的。我錯過了一些明顯的東西,這個工具是正確的嗎?提前謝謝了。

+0

@bartoli:謝謝,但是如前所述,這會導致相同的編譯器錯誤。 – orbitcowboy

+1

https://stackoverflow.com/questions/277258/how-do-i-see-a-c-c-source-file-after-preprocessing-in-visual-studio –

回答

1

該文檔還提到了這一點。 V1003診斷規則對未預處理的代碼進行操作,分析儀沒有關於將來如何使用該宏的信息。診斷規則允許識別宏中可能導致錯誤算術運算的錯誤。但有時它會失敗。存在更精確的診斷,但不幸的是,它可能會錯過大量的病例。

被引用的源代碼導致誤報,因爲分析器認爲,'< <'可以是整數值移位操作。如果這種誤報數量很大,可以禁用V1003診斷。但如果這是一個孤立的情況下,我建議使用假陽性抑制評論:

#define FRED(msg) (msg) << Z //-V1003 

這裏是一個另類。您可以使用像這樣的評論:

//-V:<<:1003 

在這種情況下,V1003診斷將不被使用了「< <」操作時觸發。此註釋可以放在全局頭文件之一(例如,stdafx.h)或診斷配置文件(.pvsconfig)中。有關這些抑制誤報的其他方法的詳細說明,請參見文檔Suppression of false alarms

2

我認爲這項警告的目標算術表達式。例如,如果是msg省略0xf & 8括號可能會產生不同的結果,因爲operator <<具有比&更高的優先級。