简体   繁体   中英

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. 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; 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 . 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. In fact, since the original is deallocated when the function returns, it causes problems as you've used it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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