Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning reference of a temporary object from a function

Consider the following code -

#include <iostream>
#include <stdio.h>

const int & retRef() {
    return 6;
}

int main()
{
    const int& k = retRef();
    printf("Value: %d\n", k);
    printf("Address: %p\n", &k);
    printf("Value: %d\n", k);
    return 0;
}

The output is -

Value: 6
Address: 0x7ffd45bf544c
Value: 32692

Why the value changed after printing the address of the variable k? If I replace the line const int& k = retRef() with const int& k = 6;, the output is as expected.

Why is this different behavior? Thanks in advance

like image 667
kuro Avatar asked Jan 01 '23 13:01

kuro


2 Answers

Your code has undefined behavior; You're trying to bind a temporary int (which is constructed from literal 6) to reference as return value, but the temporary will be destroyed immediately then retRef() always returns a dangled reference, and k is dangled too. Any dereference on it leads to UB.

Whenever a reference is bound to a temporary or to a subobject thereof, the lifetime of the temporary is extended to match the lifetime of the reference, with the following exceptions:

  • a temporary bound to a return value of a function in a return statement is not extended: it is destroyed immediately at the end of the return expression. Such function always returns a dangling reference.

On the other hand, const int& k = 6; works fine because the lifetime of temporary is extended to the lifetime of k as stated above.

like image 95
songyuanyao Avatar answered Jan 04 '23 02:01

songyuanyao


You are returning a reference to a temporary object which will cause undefined behaviour. The object will not be available once function returns.

n4659 - § 15.2:

(6.2) — The lifetime of a temporary bound to the returned value in a function return statement (9.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

like image 29
haccks Avatar answered Jan 04 '23 02:01

haccks