c++ - 引用函数按值返回和自动

标签 c++ reference constants auto

根据我的理解,当您将变量定义为对按值返回的函数的引用时,您实际上拥有对生命周期绑定(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/

相关文章:

c++ - 在指向对象的指针 vector 中取消引用

java - 如何使用依赖注入(inject)模式实现类常量静态字段声明

php - 如何检查 PHP 定义的常量的值是否等于某个值?

c++ - 我怎样才能让这个简单的程序在不关闭的情况下返回?

c++ - std::iterator::reference 必须是引用吗?

c++ - LoadString() 方法在 C++ 中不起作用

java - 在 Java 中,通过 getter 引用字段与通过变量引用字段之间是否存在性能差异?

php - 是否有可能在 php 中获取调用者上下文的魔法常量?

c++ - 在 win32 API 应用程序中实现全局化/多语言功能

c++ - 以编程方式创建纹理 DirectX