函数参数中的引用怎么办,如果函数返回时被销毁,那么const int *i
如何仍然是一个有效的指针?
const int* func(const int &x = 5)
{
return &x;
}
int main()
{
const int *i = func();
}
最佳答案
§12.2/5:
"A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call."
这意味着当 i
被初始化时,它正在获取一个临时对象的地址,该临时对象在那个时候确实存在。然而,一旦 i
被初始化,临时对象就会被销毁,而 i
将成为另一个悬空指针。
因此,是的,该函数是有效的——但是使用您编写的周围代码,您之后添加的任何试图取消引用 i
的代码都会产生未定义的行为。
关于c++ - 这是一个有效的功能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7494318/