user12002570
user12002570

Reputation: 1

Is returning a reference to a local int variable always undefined behavior

I have read that we should not return a pointer or a reference to a local variable. So in the below given example, i understand that when i wrote: return i; inside function foo, i am returning a reference to a local variable. And using that reference outside the function, will lead to undefined behavior.

#include <iostream>

const int& foo()
{
    int i = 5;
    return i;//returning reference to a local variable
}

const int& func()
{
    return 5;
}

int main()
{
    const int& ref = func();
    const int& f = foo();
    std::cout<<f<<std::endl; //I know this is undefined behavior because we're using a reference that points to a local variable 
    std::cout<<ref; //But IS THIS UNDEFINED BEHAVIOR too?
}

My question is that does the same hold true for the return statement return 5; inside function func. I am aware that in C++17 there is mandatory copy elison. So my question is directed towards all modern C++ version(C++11, C++17, etc). Does the behavior depends/differs on C++ version.

In particular, i know that the statement std::cout<<f<<std::endl; inside main is always undefined behavior because we're using a reference(dangling) that points to a local variable. But does the statement std::cout<<ref; also leads to undefined behavior. If not why and what will happen here.

PS: I might be wrong in describing what is actually happening in the first cout statement too. So please correct me if i am wrong.

Upvotes: 5

Views: 566

Answers (1)

eerorika
eerorika

Reputation: 238311

Is returning a reference to a local int variable always undefined behavior

Technically no. Returning a reference to a local variable (regardless of type) is never undefined behaviour itself. But such returned reference will always be invalid (if the variable is non-static) and indirecting through an invalid reference is always undefined behaviour.

const int& func()
{
    return 5;
}

int main()
{
    const int& ref = func();
    std::cout<<ref; //But IS THIS UNDEFINED BEHAVIOR too?
}

Yes. You indirect through an invalid reference, and behaviour is undefined.

Upvotes: 2

Related Questions