NoS*_*tAl 5 c++ type-inference c++11
我知道之间的区别的auto
,auto&
,const auto
和const auto&
(例如在"每个"循环),但有一两件事令我惊讶的是:
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
}
Run Code Online (Sandbox Code Playgroud)
那么有人可以告诉我何时x
表达式auto x = fun();
中的类型与返回值的类型不是同一类型fun()
?
R. *_*des 18
规则auto
与模板类型推导相同:
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&&
Run Code Online (Sandbox Code Playgroud)
通常,如果您需要副本,则使用auto
,如果您需要使用的引用auto&&
.auto&&
保留referene的常量,也可以绑定临时(延长其寿命).