Game Object Factory: Fixing Memory Leaks

Bunkai.Satori
  • Game Object Factory: Fixing Memory Leaks Bunkai.Satori

    Dear all, this is going to be tough: I have created a game object factory that generates objects of my wish. However, I get memory leaks which I can not fix.

    Memory leaks are generated by return new Object(); in the bottom part of the code sample.

    static BaseObject * CreateObjectFunc()
    {
        return new Object();
    }
    

    How and where to delete the pointers? I wrote bool ReleaseClassType(). Despite the factory works well, ReleaseClassType() does not fix memory leaks.

    bool ReleaseClassTypes()
    {
        unsigned int nRecordCount = vFactories.size();
        for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
        {
            // if the object exists in the container and is valid, then render it
            if( vFactories[nLoop] != NULL) 
                delete vFactories[nLoop]();
        }
        return true;
    }
    

    Before taking a look at the code below, let me help you in that my CGameObjectFactory creates pointers to functions creating particular object type. The pointers are stored within vFactories vector container.

    I have chosen this way because I parse an object map file. I have object type IDs (integer values) which I need to translate them into real objects. Because I have over 100 different object data types, I wished to avoid continuously traversing very long Switch() statement.

    Therefore, to create an object, I call vFactoriesnEnumObjectTypeID via CGameObjectFactory::create() to call stored function that generates desired object.

    The position of the appropriate function in the vFactories is identical to the nObjectTypeID, so I can use indexing to access the function.

    So the question remains, how to proceed with garbage collection and avoid reported memory leaks?

    #ifndef GAMEOBJECTFACTORY_H_UNIPIXELS
    #define GAMEOBJECTFACTORY_H_UNIPIXELS
    
    //#include "MemoryManager.h"
    #include <vector>
    
    
    template <typename BaseObject>
    class CGameObjectFactory
    {
    public:
        // cleanup and release registered object data types
        bool ReleaseClassTypes()
        {
            unsigned int nRecordCount = vFactories.size();
            for (unsigned int nLoop = 0; nLoop < nRecordCount; nLoop++ )
            {
                // if the object exists in the container and is valid, then render it
                if( vFactories[nLoop] != NULL) 
                    delete vFactories[nLoop]();
            }
            return true;
        }
    
        // register new object data type
        template <typename Object>
        bool RegisterClassType(unsigned int nObjectIDParam )
        {
            if(vFactories.size() < nObjectIDParam) vFactories.resize(nObjectIDParam);
    
            vFactories[nObjectIDParam] = &CreateObjectFunc<Object>;
            return true;
        }
    
    
        // create new object by calling the pointer to the appropriate type function
        BaseObject* create(unsigned int nObjectIDParam) const
        {
            return vFactories[nObjectIDParam]();
        }
    
    
        // resize the vector array containing pointers to function calls
        bool resize(unsigned int nSizeParam)
        {
            vFactories.resize(nSizeParam);
            return true;
        }
    
    private:
        //DECLARE_HEAP;
    
        template <typename Object>
        static BaseObject * CreateObjectFunc()
        {
            return new Object();
        }
    
    
        typedef BaseObject*(*factory)();
        std::vector<factory> vFactories;
    };
    
    
    //DEFINE_HEAP_T(CGameObjectFactory, "Game Object Factory");
    
    #endif // GAMEOBJECTFACTORY_H_UNIPIXELS
    

  • You can't clean up from inside the Factory class. It's the job of whatever code called create() to deallocate that memory later. The "cleanup" you've done just allocates and then destroys a new object of each type.

Tags
c++
Related questions and answers
  • //////////// bool move(int X, int Y) { location[0] += X; location[1] += Y; return true;}; };// end of sprite... /////////////////////////// vector &lt;string> get_contents(int comm= NEW) {switch(comm){ case NEW: return new_map; break... and traveling throug it. This is due to some odd reason for the "numb_collisions", which is used to count how many collisions have occured since initial collision (if it's 0 it means it IS the initial

  • : return DefWindowProc(hWnd, message, wParam, lParam); } } bool initDirect3D(void) { pD3D = NULL; pd3dDevice = NULL; // create the DirectX object if(NULL == (pD3D = Direct3DCreate9..._VERTEXPROCESSING, &d3dpp, &pd3dDevice))) return false; return true; } void render(void) { // check to make sure you have a valid Direct3D device if (NULL == pd3dDevice) return...\\......." ;) ================================= I have been googling for a while but still cant come up with a solution to the problem - D3DXGetImageInfoFromFile function just doesn't load any images

  • variable interface static D3D10_PASS_DESC PassDesc; // function prototypes void initD3D(HWND hWnd); void render_frame(); void init_pipeline(); void cleanD3D(); void Init(); #endif cube.cpp #include...() { } Cube::~Cube() { pBuffer->Release(); // why does this only work when put here? because it's created here? I thnk so, why not iBuffer though? } void Cube::Draw() { render_frame(); } void Cube...(); }; #endif If I call Init() from game.cpp, the code works fine, if I call cube->init(), just as this function is entered (not when the other one is left), the device pointer suddenly has an address

  • with different types of objects in the same scene. I was also thinking about making a MeshNode class and then make a Mesh object that contains them, but then I have some conflict on where to store some data... at this level I prefer to have well-defined data so I can store and work with fast during runtime. It's this complicated because it must support a lot of rendering and animation techniques, must support... for my needs. Ah and I forgot to mention that nodes can have hierarchy, but this is not a problem if the frame data is reduced. The structure instances don't get duplicated unless any value changes. When

  • To begin with I am developing a PSP application so I have no clue how to debug a PSP application. That doesn't mean I do not know how debug period. Anyway, when I run the game everything runs fine but when I press the X button on the PSP I see no bullet being drawn or updated on the screen. I know the problem doesn't lie with the pad because I press start and it exits my game so I do not think...(); missile->Init(true, s->X, s->Y); bullets->push_back(missile); } } void CleanUp() { for(unsigned int index = 0; index &lt; bullets->size(); index

  • in the shader code) for( int n = 0; n &lt; vShaderArgs.size(); n ++) glBindAttribLocation( m_nProgramId, n, vShaderArgs[n].sFieldName.c_str() ); // Create and bind to a vertex array object, which..._TRIANGLES, m_nNumIndices, GL_UNSIGNED_INT, ((char*)NULL + 0) ); glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); } Back to the Vertex Array Object though. My code for creating the Vertex

  • a soft target for the total memory used by all the game's resources combined. Other classes will create resource objects, which will be in an unloaded state, and pass them to the ResourceManager... in advance of first use. Here is a bit a sketch of the classes I am using: typedef unsigned int ResourceId; // Resource is an abstract data type. class Resource { Resource(); virtual ~Resource(); virtual bool load() = 0; virtual bool unload() = 0; virtual size_t getSize() = 0; // Used in determining how much memory is // being used. bool

  • the rigid body object btRigidBody *RigidBody = new btRigidBody(0, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->setUserPointer((void...); // CReate the rigid body object btRigidBody *RigidBody = new btRigidBody(TMass, MotionState, Shape, LocalInertia); // Store a pointer to the Ogre Node so we can update it later RigidBody->... every frame to handle input and render etc I call an UpdatePhysics method to update the physics simulation. void GameState::UpdatePhysics(unsigned int TDeltaTime) { World->stepSimulation(TDeltaTime

  • ; float current_time, old_time, interpol; int type, current_frame, next_frame; }; struct md2_glcmd_t { float s; float t; int index; }; #define MD2_IDENT (('2'&lt;&lt;24) + ('P'&lt;&lt;16..._Commands, m_MD2Header.num_glcommands * sizeof(int)); // Read all the data. for(int i = 0; i &lt; m_MD2Header.num_frames; ++i) { md2_frame_t* Frame = (md2_frame_t*)&Buffer...; int* m_Normals; unsigned int m_TextureID; float m_Scale; void Interpolate(vec3_t* Vertices); }; #include &lt;helpers/md2.h> #include &lt;iostream> #include &lt

Data information