按值和自动引用函数 return
Reference to function return by value and auto
根据我的理解,当您按值将变量定义为对函数 return 的引用时,您实际上引用了一个临时对象,该对象的生命周期绑定到该引用,并且您必须具有该引用声明为 const
.
话虽如此,为什么不将临时定义为 const
,这样下面示例中的 a2
会自动成为 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
}
您不想 return 一个 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&
绑定到临时文件的麻烦。
根据我的理解,当您按值将变量定义为对函数 return 的引用时,您实际上引用了一个临时对象,该对象的生命周期绑定到该引用,并且您必须具有该引用声明为 const
.
话虽如此,为什么不将临时定义为 const
,这样下面示例中的 a2
会自动成为 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
}
您不想 return 一个 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&
绑定到临时文件的麻烦。