Home > Blockchain >  Why are adornment to auto allowed in the return type of a function
Why are adornment to auto allowed in the return type of a function

Time:01-19

I have always thought that the only form of using auto as the return type is as follows:

auto f() { 
   return 42;
}

I have just seen code when has a const reference adornment specifier added.

int value = 42;

auto const& f() {
   return value;
}

Is this standard C ? I thought you could only use the first form with the keyword auto only which decays, ie drops cv qualifiers and references.

Can anyone share where this exists in the standard?

What are the differences between this and decltype(auto) which would do the same thing?

CodePudding user response:

Is this standard C ?

Yes.

I thought you could only use the first form with the keyword auto only which decays, ie drops cv qualifiers and references.

Well, yes, that's what will happen and if the function attempts to return a reference, for example, and a copy is made in that case. Very often that's intentional.

But if a function returns a reference to a long-winded type, and you don't want this to happen, then: rather than type out the entire novel it gets replaced by auto, keeping the &, and you move on to bigger and better things. You have better things to do then meticulously type out a ridiculous typename, that takes up most of your screen's width. The compiler already knows what it is, and you're happy to trust it.

  • Related