Why doesn't Visual Studio fire a warning at self-assignment (int foo = foo;)

前端 未结 1 500
误落风尘
误落风尘 2021-01-13 21:30

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

#include \"stdafx.h\"
#include 

        
1条回答
  •  走了就别回头了
    2021-01-13 22:12

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

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

    • The assignment of i

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

    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.

    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.

    0 讨论(0)
提交回复
热议问题