auto vs auto&& for a function return value

auto, c++, c++11, function, return-value

Solution

However, use of the universal reference auto&& does not have such a disadvantage?

No, it would not copy the return value.

The problem

However, sometimes copy is necessary, and using `auto&&` for both `prvalue` and references can create dangling references. Consider this case:

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;
}

As you can see, with `auto`, there was no problem with changing of this return value. However, with `auto&&`, it has created a dangling reference.

Conclusion

Use `auto&&` like a regular reference: treat it with caution. Using it for both `prvalue` and reference value return values may cause bad surprises.

Problem

Could you tell me please whether I am right that use of auto&& for a function return value is always a better choice than use of auto. For instance, in ``` auto val = someObj.getVal(); ``` the val will be a copy if getVal() returns a reference. However, use of the universal reference auto&& does not have such a disadvantage? The only information I need to know is whether getVal() is const or not.

Original source