根据我的理解,当您将变量定义为对按值返回的函数的引用时,您实际上拥有对生命周期绑定(bind)到该引用的临时对象的引用,并且您必须将该引用声明为 常量
。
话虽这么说,为什么不将临时定义为 const
,以便下面示例中的 a2
自动成为 const
?
如果不允许将非常量引用绑定(bind)到该临时对象,那么为什么不默认使临时对象本身 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
值,因为它会 kill move semantics .
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&
绑定(bind)到临时变量的麻烦。
关于c++ - 引用函数按值返回和自动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888233/