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
不是该函数的局部变量吗?返回它的参考不应该't be successful, isn't吗?
2 回答
编译器发出警告,表示您正在返回对局部变量的引用 .
它的工作原理是因为从函数返回对局部变量的引用是 Undefined Behavior .
未定义的行为意味着任何事情都可能发生,并且行为无法在C标准的语义中解释 .
你只是幸运,相当不幸,它的工作原理 . 它可能永远不会起作用 .
您将返回对
argA
副本的引用,因为它在您调用该函数时存在 . 当你从该函数返回时,该副本将被销毁,并且它所在的空间可以被其他东西合法地使用 .这与this question没有什么不同,除了您使用的是引用而不是指针 .