为什么Visual Studio在自我赋值时触发警告(int foo = foo;) [英] Why doesn't Visual Studio fire a warning at self-assignment (int foo = foo;)

查看:181
本文介绍了为什么Visual Studio在自我赋值时触发警告(int foo = foo;)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我重构了一个术语,出现了一个bazilion时间,当我偶然生成一个情况下的代码如下:

I was refactoring a term which appeared a bazilion time when I produce by accident a situation like in the code below:

#include "stdafx.h"
#include <iostream>

int foo = foo;

//By replaceing with the following instruction we causes a compile error
//int foo(foo);

int _tmain(int argc, _TCHAR* argv[])
{
    int bar = bar;
    std::cout << "Well this is awkward " << foo << std::endl;
    return 0;
}

对于不同的调试和发布配置,编译器默认 int foo = foo;

With different debug and release configurations the compiler is silent about int foo = foo; .

我看不到这个语句不是等待发生的错误。应该不是可视工作室编译器发出警告?

I fail to see a situation where this statement is not a bug waiting to happen. Shouldn't the visual studio compiler fire a warning?

编辑

我并不假装这是一个未定义的行为。我说,默认情况下,从一个变量到本身的赋值可能是程序员的错误。

I am not pretending this is an undefined behavior. I am saying that by default making an assignment from a variable to itself is likely to be the programmer mistake. Unless someone has a weird scheme around the use of the assignment operator.

推荐答案

类似的问题( i = i ++ )确实是未定义的行为,但它主要是因为指令包含两个赋值给同一个变量:

A similar issue (i=i++) is indeed undefined behavior, but it's mainly because the instruction contains two assignments to the same variable:


  • i ( i ++ )的递增, em> i ++ 指令返回 i

  • The incrementing of i (i++), which is done at some point after the instruction i++ returns i

分配 i

问题是不能真正知道 i 的赋值在增加之前或之后发生,因此未定义的行为。

The problem is that we can't really know if the assignment of i happens before or after incrementing, thus undefined behavior.

在您的示例中, foo = foo ,我们有一个读取,

In your example, foo=foo, we have a read, followed by a write. Unambiguously, we will have to read the value before writing to it, so it's easy to define.

一个注意事项是,如果 operator =

A side note is that if operator= is redefined, then foo=foo could do a lot of things that aren't simply a copy of foo into itself. C++ purposefully allows you to shoot yourself in the food in many different ways. But in any case C++ compilers are not the gold standard of pro-activeness in warnings/errors.

这篇关于为什么Visual Studio在自我赋值时触发警告(int foo = foo;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆