开发者

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? Return开发者_运维知识库ing its reference shouldn't be successful, isn't it?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜