简体   繁体   English

如何正确使用dispose()?

[英]How to use dispose() properly?

For example, if I have an instance of an object, which implements Disposable, let's say it is 例如,如果我有一个实现Disposable的对象的实例,那么说它是

BitmapFont someFont = new BitmapFont();

According to LibGDX documentation, I should call the dispose() method as soon as the object is no longer needed. 根据LibGDX文档,一旦不再需要该对象,我应该立即调用dispose()方法。 But what if decide to assign new font to the same variable: 但是,如果决定将新字体分配给相同的变量,该怎么办:

someFont = new BitmapFont();

Should I first call dispose() before such an assignment in order to prevent a memory leak? 我应该在这样的分配之前先调用dispose(),以防止内存泄漏吗? In other words, which variant is correct, this 换句话说,哪个变体是正确的

    BitmapFont someFont = new BitmapFont();
    //do something
    someFont.dispose();
    someFont = new BitmapFont();
    //do something else
    someFont.dispose();

or this: 或这个:

    BitmapFont someFont = new BitmapFont();
    //do something
    someFont = new BitmapFont();
    //do something else
    someFont.dispose();

I'm currently thinking that the first one is correct, and it seemes that dispose() behaves just like the destructor in C++, except for the fact that it is not called automatically. 我目前认为第一个是正确的,并且似乎dispose()的行为就像C ++中的析构函数一样,只是它不是自动调用的。

So, which version is actually correct? 那么,哪个版本实际上是正确的?

Your variable is simply a pointer to a given object, not an overarching container that holds all references that it has ever encompassed. 您的变量仅是指向给定对象的指针,而不是一个包含其曾经包含的所有引用的总体容器。 If you were to follow your second code example, you are only calling dispose on the second BitmapFont instance, not the first one. 如果要遵循第二个代码示例,则只在第二个BitmapFont实例上调用dispose,而不是第一个。 Your first pattern is technically correct, and you would want to consider try/finally blocks as well to ensure dispose is called when you are done with it. 您的第一个模式在技术上是正确的,并且您还希望考虑try / finally块,以确保在完成处理后调用该方法。

Go with your second example, the first example is also correct but the the call to the first dispose() is redundant since you are using the same pointer again. 再来看第二个例子,第一个例子也是正确的,但是对第一个dispose()的调用是多余的,因为您再次使用了相同的指针。 Good luck :) 祝好运 :)

Update : 更新:

Sorry ! 不好意思! I checked I was wrong :/ You need to call the first dispose() function in order to avoid memory leaking so the correct example is the first one 我检查了我错了:/您需要调用第一个dispose()函数以避免内存泄漏, 因此第一个示例就是正确的示例

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

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