Is returning a reference to a constant undefined?

O

Old Admiral

Gentlemen:


Is this UB?


#include <iostream>

const int& f()
{
return 3;
}

int main()
{
const int& s = f();
std::cout << s << '\n';
}


My compiler does warn me about it, but what I would like to know is
this:

Wouldn't the "const int&" part bind to the temporary like in the case
of:

const int& i = 3;

?

Thanks for your help.


Old Admiral salutes you.
OA.
 
I

Ioannis Vranos

Old said:
Gentlemen:


Is this UB?


#include <iostream>

const int& f()
{
return 3;
}

int main()
{
const int& s = f();
std::cout << s << '\n';
}


It is undefined behaviour because you *return* a reference to a local
object.


My compiler does warn me about it, but what I would like to know is
this:

Wouldn't the "const int&" part bind to the temporary like in the case
of:

const int& i = 3;


No they are not the same. But by only changing the function signature to:


const int f()


we can say that this is the same and valid.
 
V

Victor Bazarov

Old said:
Gentlemen:


Is this UB?

Yes, you're returning a reference to a local literal.
#include <iostream>

const int& f()
{
return 3;
}

int main()
{
const int& s = f();
std::cout << s << '\n';
}


My compiler does warn me about it, but what I would like to know is
this:

Wouldn't the "const int&" part bind to the temporary like in the case
of:

const int& i = 3;

?

No. In the case of

const int & i = 3;

both 3 and 'i' have the same scope. In your case, 3 disappears as soon
as the function where it exists finishes.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top