为什么Visual Studio在自我赋值时触发警告(int foo = foo;)

编程入门 行业动态 更新时间:2024-10-26 15:15:29
本文介绍了为什么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;)

本文发布于:2023-10-16 15:55:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498040.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:赋值   自我   Studio   Visual   int

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!