Aquarius_Girl
Aquarius_Girl

Reputation: 22946

Successfull return of a reference of a local variable

template <typename dataTypeA, 
          typename dataTypeB> 
                             dataTypeB const& functionX (dataTypeA argA, 
                                                         dataTypeB const& argB)
{
    return argA;
}

int main ()
{
    cout << functionX (3, 1L);
    return 0;
}

The compilation:

anisha@linux-dopx:~/Desktop/notes/c++> g++ functionTemplates.cpp -Wall -Wextra -pedantic

functionTemplates.cpp: In function ‘const dataTypeB& functionX(dataTypeA, const dataTypeB&) [with dataTypeA = int, dataTypeB = long int]’:
functionTemplates.cpp:47:26:   instantiated from here
functionTemplates.cpp:35:9: warning: returning reference to temporary

and then:

anisha@linux-dopx:~/Desktop/notes/c++> ./a.out
3

Why is it returning 3?

Isn't argA a local variable for that function? Returning its reference shouldn't be successful, isn't it?

Upvotes: 1

Views: 132

Answers (2)

You're returning a reference to the copy of argA, as it existed when you called the function. When you return from that function that copy will have been destroyed and the space it was in can quite legitimately be used by something else.

This is no different to this question, except that you're using a reference instead of a pointer.

Upvotes: 1

Alok Save
Alok Save

Reputation: 206616

The compiler issues a warning, that you are returning an reference to local variable.

It works because returning a reference to local variable from a function is Undefined Behavior.
Undefined Behavior means anything can happen and the behavior cannot be explained within the semantics of the C++ Standard.

You are just being lucky, rather unlucky that it works. It may not work always.

Upvotes: 5

Related Questions