简体   繁体   English

为什么在 function 的返回类型中允许对 auto 进行修饰

[英]Why are adornment to auto allowed in the return type of a function

I have always thought that the only form of using auto as the return type is as follows:我一直认为使用auto作为返回类型的唯一形式如下:

auto f() { 
   return 42;
}

I have just seen code when has a const reference adornment specifier added.我刚刚看到添加了 const 引用装饰说明符的代码。

int value = 42;整数值 = 42;

auto const& f() {
   return value;
}

Is this standard C++?这个标准是C++吗? I thought you could only use the first form with the keyword auto only which decays, ie drops cv qualifiers and references.我认为您只能使用带有关键字 auto only 的第一种形式,它会衰减,即删除 cv 限定符和引用。

Can anyone share where this exists in the standard?任何人都可以分享标准中存在的地方吗?

What are the differences between this and decltype(auto) which would do the same thing?这和做同样事情的 decltype(auto) 之间有什么区别?

Is this standard C++?这个标准是C++吗?

Yes.是的。

I thought you could only use the first form with the keyword auto only which decays, ie drops cv qualifiers and references.我认为您只能使用带有关键字 auto only 的第一种形式,它会衰减,即删除 cv 限定符和引用。

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.好吧,是的,如果 function 试图返回一个引用,那么就会发生这种情况,例如,在这种情况下制作了一个副本。 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.但是,如果 function 返回对冗长类型的引用,并且您不希望这种情况发生,那么:与其输入整本小说,不如将其替换为auto ,保留& ,然后您继续进行更大更更好的东西。 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.编译器已经知道它是什么,您很乐意相信它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM