Is there a downside to declaring variables with auto in C++?

后端 未结 14 2055
-上瘾入骨i
-上瘾入骨i 2020-12-12 18:14

It seems that auto was a fairly significant feature to be added in C++11 that seems to follow a lot of the newer languages. As with a language like Python, I ha

14条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 18:41

    What no one mentioned here so far, but for itself is worth an answer if you asked me.

    Since (even if everyone should be aware that C != C++) code written in C can easily be designed to provide a base for C++ code and therefore be designed without too much effort to be C++ compatible, this could be a requirement for design.

    I know about some rules where some well defined constructs from C are invalid for C++ and vice versa. But this would simply result in broken executables and the known UB-clause applies which most times is noticed by strange loopings resulting in crashes or whatever (or even may stay undetected, but that doesn't matter here).

    But auto is the first time1 this changes!

    Imagine you used auto as storage-class specifier before and transfer the code. It would not even necessarily (depending on the way it was used) "break"; it actually could silently change the behaviour of the program.

    That's something one should keep in mind.


    1At least the first time I'm aware of.

提交回复
热议问题