[英]C++11 auto and function return types
我知道auto
, auto&
, const auto
和const auto&
之間的區別(例如,在“ for each”循環中),但是令我驚訝的是:
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
}
所以有人可以告訴我表達式中x
的類型是何時auto x = fun();
將與fun()
返回值的類型不同嗎?
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&&
通常,如果要復制,請使用auto
;如果要引用,請使用auto&&
。 auto&&
保留參照原子的恆定性,並且還可以綁定到臨時對象(延長其壽命)。
在g ++-4.8中,對自動返回函數返回類型進行了增強:
2012-03-21 Jason Merrill
Implement return type deduction for normal functions with -std=c++1y.
您需要-std = c ++ 1y或-std = gnu ++ 1y標志。
這有效:auto sluggo(){return 42; }
int
main()
{
auto s1 = sluggo();
s1 += 7;
}
OP問題僅按預期在+="YYY"
上出現錯誤。 您甚至可以使用auto聲明cf:
#include <string>
std::string bla;
const auto&
cf()
{
return bla;
}
int
main()
{
auto s1 = cf();
const std::string& s2 = cf();
s1 += "XXX"; // not an error
s2 += "YYY"; // error as expected
}
它仍然在+="YYY"
上出錯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.