传递函数的返回值作为引用

时间:2021-08-12 20:36:04

What is supposed to happen in the following case:

在以下情况下会发生什么:

int functionA() {
    return 25;
}

void functionB(const int& ref) {
    cout << ref << endl;
}

void start() {
    functionB(functionA());
}

When compiling this example, it outputs the correct value 25. How does this work? Should'nt the referenced return value on the stack be deleted (removed from the stack) when using only a reference to it, or is the behaviour undefined?

在编译这个示例时,它输出正确的值25。这是如何工作的呢?当只使用对堆栈的引用时,是否应该删除堆栈上的引用返回值(从堆栈中删除),还是不定义行为?

2 个解决方案

#1


8  

This "works" because of const int& ref - when a reference is const (guarantees that you don't want to change it), the compiler will produce a temporary object in the calling code (start in your case), and then pass the reference to that.

这个“工作”是因为const int&ref——当引用是const(保证您不想更改它)时,编译器会在调用代码中生成一个临时对象(在您的例子中开始),然后将引用传递给它。

If you remove const it will fail to compile because functionA's result can't be turned into a reference.

如果删除const,它将无法编译,因为无法将functionA的结果转换为引用。

#2


8  

There is no "return value on the stack" (let alone a "stack"): functionA returns an int by value, so the expression functionA() is simply a temporary value of type int. This value binds to the constant reference in functionB, and since its lifetime is that of the full expression, everything is fine.

没有“返回值栈”(更不用说“堆栈”):功能阳极返回一个int值,所以表达式功能阳极()只是一个临时的int类型的值。这个值绑定到functionB常数引用,因为它的生命周期的完整表达,一切都很好。

#1


8  

This "works" because of const int& ref - when a reference is const (guarantees that you don't want to change it), the compiler will produce a temporary object in the calling code (start in your case), and then pass the reference to that.

这个“工作”是因为const int&ref——当引用是const(保证您不想更改它)时,编译器会在调用代码中生成一个临时对象(在您的例子中开始),然后将引用传递给它。

If you remove const it will fail to compile because functionA's result can't be turned into a reference.

如果删除const,它将无法编译,因为无法将functionA的结果转换为引用。

#2


8  

There is no "return value on the stack" (let alone a "stack"): functionA returns an int by value, so the expression functionA() is simply a temporary value of type int. This value binds to the constant reference in functionB, and since its lifetime is that of the full expression, everything is fine.

没有“返回值栈”(更不用说“堆栈”):功能阳极返回一个int值,所以表达式功能阳极()只是一个临时的int类型的值。这个值绑定到functionB常数引用,因为它的生命周期的完整表达,一切都很好。

相关文章