簡體   English   中英

引用函數按值和auto返回

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM