Why can't I directly return reference to a pointer from a function returning a pointer?

Viewed 54

In C++, this code does not compile:

double* value() {
    return nullptr;
}

double*& function() {
    return value();
}

Error: Non-const lvalue reference to type 'double *' cannot bind to a temporary of type 'double *'

However, this code does compile without errors:

double* value() {
    return nullptr;
}

double*& function() {
    double* valueVar = value();
    return valueVar;
}

Can someone explain to me why? I would've thought they did exactly the same thing, to me the second code just looks redundant.

1 Answers

value() returns pointer by value, what it returns is an rvalue and can't be bound to lvalue-reference to non-const like double* &, so your 1st code snippet doesn't compile.

In the 2nd code snippet you're binding a local object to the reference. valueVar is an lvalue and could be bound to the lvalue-reference to non-const, but note that the local object will be destroyed when the function returns, then the returned reference will always be dangled, any dereference on it leads to UB.

Related