问题描述
我以前认为返回一个引用是坏的,因为我们返回的引用会引用一些垃圾值。但这个代码工作( matrix
是一个类):
I used to think returning a reference is bad as our returned reference will refer to some garbage value. But this code works (matrix
is a class):
const int max_matrix_temp = 7;
matrix&get_matrix_temp()
{
static int nbuf = 0;
static matrix buf[max_matrix_temp];
if(nbuf == max_matrix_temp)
nbuf = 0;
return buf[nbuf++];
}
matrix& operator+(const matrix&arg1, const matrix&arg2)
{
matrix& res = get_matrix_temp();
//...
return res;
}
buf
推荐答案
我看不到 buf
在任何地方声明,这意味着它不会超出范围与函数返回,所以没关系。 (它实际上看起来像是 matrixbuf
这也很好,因为它 static
)。
I see no buf
declared anywhere, which means it doesn't go out of scope with function return, so it's okay. (it actually looks like it's meant to be matrixbuf
which is also fine, because it's static
).
编辑:感谢R. Martinho Fernandes的猜测。当然是 matrix buf
,所以它使得 buf
静态数组,其中临时被分配以确保它'当函数返回时,获得释放,因此返回值仍然有效。
Thanks to R. Martinho Fernandes for the guess. Of course it is matrix buf
, so it makes buf
static array in which temporary is allocated to make sure it doesn't get freed when the function returns and therefore the return value is still valid.
这篇关于返回引用可以工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!