4

我不确定我是否理解范围 - 范围外的变量(我正在使用 Ruby)是否存在于内存中的某个地方,或者它是否停止存在(我知道你无法访问它)。说一个超出范围的变量不再存在是不准确的吗?

也许这是一个哲学问题。

4

7 回答 7

5

If you are using managed language then you don't allocate and unallocate memory so as far as you are concerned it no longer exists.

Technically it does but GCs tend not to be deterministic so technically it's hard to say when it actually vanishes.

于 2009-03-02T17:40:35.400 回答
3

变量与其所持有的值不同。

当变量超出范围时,变量本身将不复存在。变量持有的可能代表一个对象,并且该对象可能在变量的生命周期之后继续存在。垃圾收集器稍后会回收该对象。

于 2009-03-02T17:24:15.360 回答
2

当它超出范围时,它仍然存在(从某种意义上说,它分配了一些内存)一段时间,直到垃圾收集清理它。但正如您所暗示的那样,它已经失去了它的名字并且无法到达。

于 2009-03-02T16:35:23.450 回答
2

当变量超出范围时,周围是否有人听到它的尖叫声?

这不是一个红宝石问题,而是一个关于垃圾收集的一般问题。在 Ruby 或 C# 等垃圾收集语言中,当变量超出范围时,它会以某种方式被标记为不再使用。发生这种情况时,您将无法再使用它,它会四处转动拇指-但它仍然分配有内存。

在某个时候,垃圾收集器会唤醒并查找标记为未使用的变量。它会处理掉它们,到那时它们就不再存在于记忆中了。

它可能比这更复杂,这取决于垃圾收集器的工作方式,但它已经足够接近了:)

于 2009-03-02T16:36:58.157 回答
1

它存在一段时间,直到垃圾收集器处理它(如果可以的话)。

于 2009-03-02T16:34:55.153 回答
1

Rob Kennedy 对此进行了适当的回答,但我想我会添加更多细节。

要认识到的重要一点是变量与其所代表的值之间的差异。

这是一个示例(在 C# 中,因为我不了解 Ruby):

object c = null;
if (1 == 1) // Just to get a different scope
{
    var newObj = new SomeClass();
    newObj.SomeProperty = true;
    c = newObj;
}

在上面的代码中,newObj 在 if 语句的末尾超出了范围,因此“不存在”,但它所引用的值仍然存在并且被 c 引用。一旦对对象的所有引用都消失了,垃圾收集器将负责清理它。

于 2009-03-02T17:37:15.937 回答
0

If you're talking about file objects, it becomes more than a philosophical question. If I recall correctly, files do not close automatically when they go out of scope - they only close if you ask them to close, or if you use a File.open do |file| style block, or if they get garbage collected. This can be an issue if other code (or unit tests) try to read the contents of that file and it hasn't yet been flushed.

于 2009-03-02T22:09:36.907 回答