成功返回局部变量的引用
template <typename dataTypeA,
typename dataTypeB>
dataTypeB const& functionX (dataTypeA argA,
dataTypeB const& argB)
{
return argA;
}
int main ()
{
cout << functionX (3, 1L);
return 0;
}
编译:
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
然后:
anisha@linux-dopx:~/Desktop/notes/c++> ./a.out
3
为什么它返回3?
argA 不是该函数的局部变量吗?返回其引用应该不会成功,不是吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器发出警告,表明您正在返回对局部变量的引用。
它之所以有效,是因为从函数返回对局部变量的引用是未定义行为。
未定义的行为意味着任何事情都可能发生,并且该行为无法在 C++ 标准的语义内解释。
你只是幸运,而不是不幸它有效。它可能并不总是有效。
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.
您将返回对
argA
副本的引用,因为它在您调用该函数时就已存在。当您从该函数返回时,该副本将被销毁,并且它所在的空间可以完全合法地被其他东西使用。这与这个问题没有什么不同,只不过您使用的是引用而不是指针。
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.