C ++ auto - convenience and confusion

I am starting to compile C ++ 11 and at the moment I have a love-and-hate for "auto".

It's convenient, no doubt.

But this is confusing too, here is the code:

auto w = foo->get_w();
auto i = w->get_i();
bar(i);

      

In this code, the function get_w()

returns "struct S *", which is a w-type. But struct S has 2 get_i () overloaded:

const I* get_i() const;
unique_ptr<I>& get_i();

      

Since w is not const

, so it gets called second get_i()

, so it bar(i)

should be bar(move(i))

, because the signature is bar () void bar(unique_ptr<I>)

.

But it's actually easy to lose track.

It's a good thing it's caught at compile time, but I think my initial enthusiasm is waning.

What do you think? Any feedback?

+3


source to share


2 answers


For that matter, I need to link this great article from Herb Sutter: GotW # 94 Solution: AAA style (almost always automatic) .

You can read his opinion already from the title. He also brings up this guide, the rationale for which is explained in the article:



Recommendation: Remember that preferred variables are auto

motivated primarily by correctness, performance, maintainability, and reliability - and only ultimately about usability.

The main aspects auto

it praises are that it avoids unwanted implicit conversions, of which there are many in C ++, and that it makes callers less dependent on function interfaces, since changing the return type is automatically reflected in the type of local variables. auto

also very useful in template code since you don't need to access eg. Container::value_type

...

+4


source


It depends. Whenever it is more convenient than obfuscation, use it, otherwise not. For a long list of arguments and opinions, I will refer to another, different question: Using the var keyword in C #



+2


source







All Articles