Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reference and literals in C++

Tags:

c++

rvalue

I know that "literals" (c strings, int or whatever) are stored somewhere (in a read only data section apparently .rodata) maybe this is not accurate...

I want to understand why this code causes a runtime error:

#include <iostream>
using namespace std;

const int& foo()
{
    return 2;
}
const char* bar()
{
    return "Hello !";
}

int main() {

    cout << foo() << endl; // crash

    cout << bar() << endl; // OK

    return 0;
}

foo returns a const reference on a literal (2) why does this cause a crash ? is the integer 2 stored in the stack of foo() ?

See also : Why are string literals l-value while all other literals are r-value?

like image 364
Aminos Avatar asked Feb 05 '23 22:02

Aminos


1 Answers

I see why this is confusing so I will try to break it down.

First case:

const int& foo()
{
    return 2;
}

The return statement makes a temporary object which is a copy of the literal 2. So its address is either non-extant or different from the location of the literal 2 (assuming literal 2 has a location - not guaranteed).

It is that temporary whose reference is returned.

Second case:

const char* bar()
{
    return "Hello !";
}

The return statement makes a temporary object which is a copy of a pointer to the address of the first element of the literal char array. That pointer contains the actual address of the literal array and that address is returned by copy to the caller.

So to sum up. The second one works because the return statement takes a copy of the literal's address and not a copy of the literal itself. It doesn't matter that the storage for the address is temporary because the address still points to the correct place after the temporary holding its value collapses.

like image 177
Galik Avatar answered Feb 08 '23 10:02

Galik