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

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

    This isn't a drawback of auto in a principled way exactly, but in practical terms it seems to be an issue for some. Basically, some people either: a) treat auto as a savior for types and shut their brain off when using it, or b) forget that auto always deduces to value types. This causes people to do things like this:

    auto x = my_obj.method_that_returns_reference();
    

    Oops, we just deep copied some object. It's often either a bug or a performance fail. Then, you can swing the other way too:

    const auto& stuff = *func_that_returns_unique_ptr();
    

    Now you get a dangling reference. These problems aren't caused by auto at all, so I don't consider them legitimate arguments against it. But it does seem like auto makes these issue more common (from my personal experience), for the reasons I listed at the beginning.

    I think given time people will adjust, and understand the division of labor: auto deduces the underlying type, but you still want to think about reference-ness and const-ness. But it's taking a bit of time.

提交回复
热议问题