D
D
Daniil Demidko2015-12-16 06:06:56
C++ / C#
Daniil Demidko, 2015-12-16 06:06:56

C++11, C++14. Is using auto a sign of bad taste?

C++11 and 14 brought a lot of new goodies. It so happened that I started dealing with them quite recently.
For example auto in a function declaration. It seems to me that this may not be a good thing at all.

auto Func()
{
    // ...
    int a=0;
    // код код и еще код
    // ...
    return a+1;
}
// ... 
// Где нибудь внизу
auto var=Func();
// ...

I understand the use of auto in loops, but here?
Is this really normal or should auto be avoided?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2015-12-16
@Daniro_San

Such good advice here...
And the rule is nowhere simpler: if you ALREADY have enough information to work with the value without specifying the type, then you can use auto. If you feel that you do not have, or doubt that you have, it is better to indicate the type. An example where using auto is great is iterators:

std::list<int> items;
auto i = items.cbegin();

The second line clearly says - items.cbegin - a constant iterator over items, running from the beginning of the list. This is more than enough for me. Specifying the type std::list<int>::const_iteratorwill not bring me any new information. Moreover, because Because since since iterators from different containers are incompatible, I also need to know right away which specific list I have an iterator for - I will again look at items.cbegin, and not at the type.
But auto in function/method declarations is really useless. By the way, it was not even allowed to be used there right away (only in C ++ 14). The reason for this is again readability - in order to understand what a function returns, you need to read its text at least until the first return, and better - completely. The only scenario where auto is indispensable when specifying the return type is arrow notation with decltype, but I don't think you'll come across it anytime soon.

J
jackroll, 2015-12-16
@jackroll

Keep figuring it out.

R
romy4, 2015-12-16
@romy4

If you're working with objects, auto is sometimes easier to understand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question