简体   繁体   English

当函数签名在名称前面有“&”时,这意味着什么?

[英]What does it mean when a function signature has “&” before the name?

int &sum(int numa, int numb)
{
    int sum = 0;
    sum = suma+sumb;
    return sum;
}  

Is this function correct? 这个功能是否正确? Why does it use & ? 为什么使用&

ADDED COMMENT: thank you all. 添加评论:谢谢大家。 But after I compiled it using gcc, it came up one warning but no error. 但是在我使用gcc编译它之后,它出现了一个警告,但没有错误。 It can run perfectly. 它可以完美运行。 Still wrong? 还是错的? or just a warning issue? 或只是一个警告问题? -

The & means you're returning a reference. &表示您正在返回参考。 In your case, you're returning a reference to an int , one that disappears as soon as the function returns; 在您的情况下,您将返回对int的引用,该函数在函数返回后立即消失; this is a serious bug. 这是一个严重的错误。

This function tries to return a reference to an integer. 此函数尝试返回对整数的引用。 Since the integer is local to the function, this definition is not valid; 由于整数是函数的局部,因此该定义无效; the integer will go out of scope once the function returns. 函数返回后,整数将超出范围。

不,你不能返回对局部变量的引用。

除了返回对本地变量的引用之外,这是一个邪恶的化身,除非在全局范围内声明sumasumb ,否则该函数使用不存在的名称。

Look up C++ References . 查找C ++参考资料 It is not safe to return references (or pointers) to local variables. 将引用(或指针)返回给局部变量是不安全的。 The local variable will be destroyed after the function exits and your returned pointer will point to undefined memory. 函数退出后,局部变量将被销毁,返回的指针将指向未定义的内存。

Since most of the above answers have cleared up the idea of a returned reference, I thought I would be a bit more precise with respect to the idea of it being "deallocated". 由于上面的大多数答案已经清除了返回引用的想法,我认为对于它被“解除分配”的想法我会更精确一些。

Functions calls place their arguments and automatic (locally declared) variables on the stack in memory. 函数调用将其参数和自动(本地声明的)变量放在内存中的堆栈上。 When a function returns, that memory is not zeroed out. 当函数返回时,该内存不会被清零。 The values are left alone, and that memory is reused for later functions as the stack grows. 值保持不变,随着堆栈的增长,该内存将重用于以后的函数。

So when you use this returned reference, it could be valid for a little bit, but then random data meant for other functions will write to the same spot, presenting you with garbage data. 因此,当您使用此返回的引用时,它可能会有一点点有效,但随后用于其他函数的随机数据将写入同一位置,向您显示垃圾数据。

& indicates that a reference to a variable is returned. &表示返回对变量的引用。 This can help in cases where the original is a larger object because it saves having to make a copy of it in some cases. 这可以在原件是较大的对象的情况下提供帮助,因为在某些情况下它可以节省必须复制它。

However, I see no reason to do this for an int. 但是,我认为没有理由为int做这个。 In fact, since the original is deallocated when the function returns, it causes problems as you've used it here. 事实上,由于原始函数在函数返回时被释放,因此在此处使用时会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM