auto vs auto&& for a function return value

Question

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.


Show source
| function   | c++   | c++11   | return-value   | auto   2016-10-31 08:10 1 Answers

Answers ( 1 )

  1. 2016-10-31 09:10

    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 {
        // Another programmer changed it from:
        // int getVal() { return mInteger; }
    
        int &getVal() { return mInteger; }
    
    private:
        int mInteger;
    }
    
    int main() {
        A *a = new A;
    
        auto   integerCopy = a->getVal();
        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.

◀ Go back