调用非void函数而不使用其返回值。实际发生了什么? [英] Calling a non-void function without using its return value. What actually happens?
问题描述
So, I found a similar question here, but the answers are more about style and whether or not you are able to do it.
我的问题是,当你打电话给你时,会发生什么?非空函数返回一个对象,但你从来没有分配或使用所返回的对象?因此,不管你是否可以,因为我绝对知道你可以和理解上面的其他问题...编译器/运行时环境做什么?
My question is, what actually happens when you call a non-void function that returns an object, but you never assign or use said returned object? So, less about whether or not you can, because I absolutely know you can and understand the other question linked above... what does the compiler/runtime environment do?
这不是一个特定于语言的问题,但如果您回答,请指定您要引用的语言,因为行为会有所不同。
This is not a language specific question, but if you answer, please specify what language you are referring to, since behaviors will differ.
推荐答案
p>我相信对于C#和Java,结果最终在堆栈上,然后编译器强制pop指令忽略它。 Eric Lippert的博文空洞是不变的有关于此的一些更多信息。
I believe that for both C# and Java, the result ends up on the stack, and the compiler then forces a pop instruction to ignore it. Eric Lippert's blog post on "The void is invariant" has some more information on this.
例如,考虑以下C#代码:
For example, consider the following C# code:
using System;
public class Test
{
static int Foo() { return 10; }
public static void Main()
{
Foo();
Foo();
}
}
由MS C#4编译器生成的IL Main
方法是:
The IL generated (by the MS C# 4 compiler) for the Main
method is:
.method public hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: call int32 Test::Foo()
L_0005: pop
L_0006: call int32 Test::Foo()
L_000b: pop
L_000c: ret
}
注意对 pop
的调用 - 如果你使 Foo
为void方法就会消失。
Note the calls to pop
- which disappear if you make Foo
a void method.
这篇关于调用非void函数而不使用其返回值。实际发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!