[英]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.