[英]Reference to function return by value and auto
從我理解的原因來看,當你將一個變量定義為一個函數返回值的引用時,你實際上有一個臨時對象的引用,其生命周期與引用綁定,你必須將該引用聲明為const
。
話雖如此,為什么臨時定義為const
不會使下面例子中的a2
自動為const
?
如果不允許將非const引用綁定到該臨時對象,那么為什么不默認使臨時對象本身為const
? 保持非常量的原因是什么?
#include <string>
std::string getStringA()
{
std::string myString = "SomeString";
return myString;
}
const std::string getStringB()
{
std::string myString = "SomeString";
return myString;
}
int main()
{
const std::string temp;
std::string &a1 = getStringA(); // std::string& a1, warning C4239 : nonstandard extension used : 'initializing' : conversion from 'std::string' to 'std::string &'
auto &a2 = getStringA(); // std::string& a2, warning C4239 : nonstandard extension used : 'initializing' : conversion from 'std::string' to 'std::string &'
const std::string &a3 = getStringA(); // all good
auto &b1 = getStringB(); // const std::string& b1
auto &b2 = temp; // const std::string& b2
}
你不想返回一個const
值,因為它會殺死移動語義 。
struct A {
A() = default;
A(A&&) = default;
A(A const&) = delete;
};
A foo() { return {}; }
A const bar() { return {}; }
int main()
{
A a1 {foo()};
A a2 {bar()}; // error here
}
這是付出太多的代價,只是為了省去自己輸入auto const&
綁定到臨時的麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.