引用函数按值和自动返回
Reference to function return by value and auto
从我理解的原因中,当您将变量定义为对函数返回的函数返回时,您实际上对具有终生绑定到参考的临时对象的引用,您必须将该参考称为const
。
话虽如此,为什么临时定义为const
,以至于以下示例中的a2
自动将是const
?
如果不允许您绑定对该临时对象的非const引用,那么为什么不默认情况下将临时对象本身const
限制为呢?将其保持非con的原因是什么?
#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&
的麻烦,以绑定到临时。
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数