How to free a static member variable in C ++?

Can someone explain how to free the memory of the static member Variable? In my opinion, it can only be freed if all instances of the class are destroyed. I am a little helpless at this moment ...

Code for explanation:

class ball
{
    private:
    static SDL_Surface *ball_image;
};
//FIXME: how to free static Variable?
SDL_Surface* ball::ball_image = SDL_LoadBMP("ball.bmp");
+5
source share
8 answers

From the sound of this, you really don't want a pointer. In fact, since this comes from the factory function in the C library, this is not a "first-class" C ++ pointer. For example, you cannot safely deletehim.

The real problem (if any) is to call SDL_FreeSurfaceit before the program exits.

-.

struct smart_sdl_surface {
    SDL_Surface *handle;

    explicit smart_sdl_surface( char const *name )
        : handle( SDL_LoadBMP( name ) ) {}
    ~smart_sdl_surface()
        { SDL_FreeSurface( handle ); }
};

class ball
{
    private:
    static smart_sdl_surface ball_image_wrapper;
    static SDL_Surface *& ball_image; // reference to the ptr inside wrapper
};
smart_sdl_surface ball::ball_image_wrapper( "ball.bmp" );
SDL_Surface *&ball::ball_image = ball::ball_image_wrapper.handle;

, . , .

+11

, . , , . .

, , :

  • . , . , , (, , ), .

  • , , . , , , 0.

  • , , , .

  • , , . , .

  • auto_ptr. , , .

4, , 5, , .

+12

. , , :

SDL_FreeSurface(ball_image);

ball_image 0, , .

"" ball, . ball ball. , , - - ( ) , , DLL, . - , (1) , , pointee, (2) , .

+3

, , .

+1

, . . , , , , .

+1

, , , - " " ResourceManager - .

ResourceManager , , , .

, , , .

+1

- . , , . , , .

, , . , -, , .

0

static variable, , smart_pointer , .

Clearing the memory of static variables in destructorwill not work for the following case: Because static members exist as members of the clas, not how instance in each object of the class. Therefore, if someone accesses a static variable with ::and dynamically allocates memory, destructorit will not be displayed, and the memory will not be deleted, since there is no object created.

0
source

All Articles