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

后端 未结 14 2065
-上瘾入骨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:32

    Like this developer, I hate auto. Or rather, I hate how people misuse auto.

    I'm of the (strong) opinion that auto is for helping you write generic code, not for reducing typing.
    C++ is a language whose goal is to let you write robust code, not to minimize development time.
    This is fairly obvious from many features of C++, but unfortunately a few of the newer ones like auto that reduce typing mislead people into thinking they should start being lazy with typing.

    In pre-auto days, people used typedefs, which was great because typedef allowed the designer of the library to help you figure out what the return type should be, so that their library works as expected. When you use auto, you take away that control from the class's designer and instead ask the compiler to figure out what the type should be, which removes one of the most powerful C++ tools from the toolbox and risks breaking their code.

    Generally, if you use auto, it should be because your code works for any reasonable type, not because you're just too lazy to write down the type that it should work with. If you use auto as a tool to help laziness, then what happens is that you eventually start introducing subtle bugs in your program, usually caused by implicit conversions that did not happen because you used auto.

    Unfortunately, these bugs are difficult to illustrate in a short example here because their brevity makes them less convincing than the actual examples that come up in a user project -- however, they occur easily in template-heavy code that expect certain implicit conversions to take place.

    If you want an example, there is one here. A little note, though: before being tempted to jump and criticize the code: keep in mind that many well-known and mature libraries have been developed around such implicit conversions, and they are there because they solve problems that can be difficult if not impossible to solve otherwise. Try to figure out a better solution before criticizing them.

提交回复
热议问题