简体   繁体   English

为什么以下代码不会在MSVC中生成警告

[英]Why does the following code not generate a warning in MSVC

I have a section of code that can be summarised as follows; 我有一段代码可以总结如下;

void MyFunc()
{
   int x;
'
'
   x;  
'
'
}

I would have thought that simply referencing a variable, without modifying it in anyway or using its value in anyway should generate a warning. 我原本以为只是引用一个变量,无论如何都不修改它或者无论如何都要使用它的值应该产生一个警告。 In VS2003 it does neither, and it I need lint to pick it up. 在VS2003中它既不会,也不需要lint来拾取它。

I realise it doesn't effect execution, but since it is a piece of code that does nothing, and the programmer doubtless intended to do something, why is it not flagged? 我意识到它不会影响执行,但由于它是一段什么都不做的代码,程序员无疑打算做某事,为什么它没有被标记?

Similarly would you expect x = x to be a warning? 同样,你会期望x = x是警告吗?

Edit: Modified question, as this constitutes a good candidate for a warning, but is not an error. 编辑:修改过的问题,因为这构成了警告的良好候选者,但不是错误。 Replies suggest this is handled better with other compilers. 回复表明,其他编译器可以更好地处理这个问题。 Will try out VS2008 later and post result. 稍后会试用VS2008并发布结果。

Such code might occur in a template class for metaprogramming purposes. 此类代码可能出现在模板类中,用于元编程目的。 For example, it might be some kind of a check whether x is accessible from the current context. 例如,可能是某种检查是否可以从当前上下文访问x Yes, it doesn't affect the result of execution , but it does affect the result of compilation ; 是的,它不会影响 执行结果,但确实会影响 编译结果; this might be of aid to techniques like SFINAE . 这可能有助于像 SFINAE这样的技术。

It seems, that it's of no help to compilation either. 看来,编译也无济于事。 Funciton bodies don't count for choosing the proper template for a function call. 函数体不计入为函数调用选择适当的模板。 And to check accessibility within a scope of a class, you have to use using operator for dependent names; 要检查类范围内的可访问性,必须using运算符作为依赖名称; this using operator itself being an accessibility check. using运算符本身是一个可访问性检查。

So, the code x; 所以,代码x; really has no effect. 真的没有效果。

You'd expect a warning unless you cast the expression to void, ie 除非你将表达式转换为void,否则你会发出警告

void MyFunc()
{
   int x;

   (void)x;  

}

What warning level do you have set ? 你设定了什么警告级别?

You need to use a better compiler :-) Compiled with the -Wall and -pedantic flags, the GCC C++ compiler given this code: 您需要使用更好的编译器:-)使用-Wall和-pedantic标志编译,GCC C ++编译器给出以下代码:

int main() {
    int x = 0;
    x;
}

produces this diagnostic: 产生这种诊断:

ma.cpp:3: warning: statement has no effect

Both single-variable statements (such as x; ) and self-assignment (such as x=x ) are valid code in C++, so the compiler can't flag them as errors, but a good compiler is of course allowed to give a warning that they don't have any effect, and might be mistakes by the programmer. 单变量语句(例如x; )和自赋值(例如x = x )都是C ++中的有效代码,因此编译器不能将它们标记为错误,但是一个好的编译器当然可以给出一个警告他们没有任何影响,可能是程序员的错误。 For example, the compiler g++ gives the warning "statement has no effect" for x; 例如,编译器g ++为x提供警告“语句无效” ; .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM