C ++ 11自动和函数返回类型 [英] C++11 auto and function return types

查看:133
本文介绍了C ++ 11自动和函数返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 auto auto& const auto const auto& (例如在for each循环中),但令我惊讶的是:

I know of the difference between auto, auto&, const auto and const auto& (for example in a "for each" loop), but one thing that surprised me is:

std::string bla;
const std::string& cf()
{
    return bla;
}


int main (int argc, char *argv[])
{
    auto s1=cf();
    const std::string& s2=cf();
    s1+="XXX"; // not an error
    s2+="YYY"; //error as expected
}

因此,有人可以告诉我什么类型的<$在表达式 auto x = fun(); 中的c $ c> x 将不是与返回值类型相同的类型 fun()

So can somebody tell me when the type of x in the expression auto x = fun(); won't be the same type as the type of the return value of the fun()?

推荐答案

auto 与模板类型推导相同:

The rules for auto are the same as for template type deduction:

template <typename T>
void f(T t); // same as auto
template <typename T>
void g(T& t); // same as auto&
template <typename T>
void h(T&& t); // same as auto&&

std::string sv;
std::string& sl = sv;
std::string const& scl = sv;

f(sv); // deduces T=std::string
f(sl); // deduces T=std::string
f(scl); // deduces T=std::string
f(std::string()); // deduces T=std::string
f(std::move(sv)); // deduces T=std::string

g(sv); // deduces T=std::string, T& becomes std::string&
g(sl); // deduces T=std::string, T& becomes std::string&
g(scl); // deduces T=std::string const, T& becomes std::string const&
g(std::string()); // does not compile
g(std::move(sv)); // does not compile

h(sv); // deduces std::string&, T&& becomes std::string&
h(sl); // deduces std::string&, T&& becomes std::string&
h(scl); // deduces std::string const&, T&& becomes std::string const&
h(std::string()); // deduces std::string, T&& becomes std::string&&
h(std::move(sv)); // deduces std::string, T&& becomes std::string&&

一般来说,如果您想要一份副本,请使用 auto ,如果你想要一个引用你使用 auto&& auto&&& 保留引用的常数,也可以绑定到临时表达式(延长其生命周期)。

In general, if you want a copy, you use auto, and if you want a reference you use auto&&. auto&& preserves the constness of the referene and can also bind to temporaries (extending their lifetime).

这篇关于C ++ 11自动和函数返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆