簡體   English   中英

auto與auto &&&函數返回值

[英]auto vs auto&& for a function return value

您能告訴我我是否正確,將auto &&用作函數返回值總是比使用auto更好的選擇。 例如,在

auto val = someObj.getVal();

如果getVal()返回引用,則val將是一個副本。 但是,使用通用引用auto &&不會有這樣的缺點嗎? 我需要知道的唯一信息是getVal()是否為const。

但是,使用通用引用auto &&不會有這樣的缺點嗎?

不,它不會復制返回值。

問題

但是,有時需要復制,並且對prvalue和引用同時使用auto&&可以創建懸掛的引用。 考慮這種情況:

struct A {
    // A: Another programmer changed it from:
    // int getVal() { return mInteger; }

    // B
    int &getVal() { return mInteger; }

private:
    int mInteger;
};

int main() {
    A *a = new A;

    auto   integerCopy = a->getVal();

    // int& on case B, int&& on case A.
    auto&& integerRvalueRef  = a->getVal();

    delete a;

    // Ok, no matter what getVal returns.
    std::cout << integerCopy;
    // Dangling Reference dereference if getVal returns a reference. 
    std::cout << integerRvalueRef;
}

如您所見,使用auto ,更改此返回值沒有問題。 但是,使用auto&& ,它創建了一個懸空引用。

結論

像常規參考一樣使用auto&& :謹慎對待。 將其用於prvalue和參考值返回值可能會導致嚴重的意外情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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