简体   繁体   中英

How to use dispose() properly?

For example, if I have an instance of an object, which implements Disposable, let's say it is

BitmapFont someFont = new BitmapFont();

According to LibGDX documentation, I should call the dispose() method as soon as the object is no longer needed. 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? 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.

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. 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.

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. 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

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