Kobi
Kobi

Reputation: 878

lifetime extension returning reference from function

Is the following UB (undefined-behavior) ? Is it really one level "too much" that value is now dangling and there is no lifetime extension done by the compiler/language rules?

const int &get_value(const int &value) { return value; };
int main()
{
    const auto &value = get_value(5);
    printf("Value is: %d", value);
}

Upvotes: 0

Views: 59

Answers (1)

H.S.
H.S.

Reputation: 12669

Yes, this is UB. When passing by 5 to get_value(), a temporary object is created and function parameter const reference value bind to it. Since, the temporary object bound to function parameter value, it will persist until the completion of the full expression containing the call. In the main(), you are dereferencing a reference which is not bound to a living object and this is undefined bahavior.

Upvotes: 2

Related Questions