c++ breaks on class function

删除回忆录丶 提交于 2019-12-14 03:30:25

问题


i have created this class for mesh loading it works but i added this new function to help speed up the loading. when i call the function my program breaks/stops.
here is my function

bool CXFileEntity::LoadXFile(const std::string &filename, int startAnimation, CXFileEntity *entity, LPDIRECT3DDEVICE9 d3ddev)
{
    // We only support one entity so if it already exists delete it
    if (entity)
    {
        delete entity;
        entity=0;
    }

    // Create the entity
    entity=new CXFileEntity(d3ddev);
    if (Load(filename))
    {
        delete entity;
        entity=0;
        return false;
    }

    SetAnimationSet(startAnimation);

    return true;
}

回答1:


EDIT: Wait... I hadn't realized that this function is a member of the CXFileEntity class. It doesn't look like it's a static method, either. So in order to call this function, you already need to have instantiated a CXFileEntity object! Therefore, it's likely that you absolutely do not want to be either deleting or creating CXFileEntity objects inside of this method. (If you truly only allow one entity to exist at a time, you'll be effectively deleting 'this' and then trying to re-create it. That doesn't work, no way, no how.)

I'm leaving the earlier answer in place in hopes that it will still provide you some clue about how pointers work.


You'd do better to give more information, such as where and how the program breaks.

But this is clearly wrong:

CXFileEntity *entity, 

because it means that the new object allocated by

entity=new CXFileEntity(d3ddev);

will not be seen by the caller. (entity is a local variable, so changes to it won't be seen outside of the local scope.)

Try changing the code to pass entity as a pointer to a pointer:

CXFileEntity **entity, 

which will mean changing the code inside the function to match:

if (*entity)
{
    delete *entity;
    *entity=0;
}

// Create the entity
*entity=new CXFileEntity(d3ddev);

// etc.

You'll also have to change the caller to pass a pointer to a pointer. And for goodness' sake, make sure that the first time you pass the pointer in, it's initialized to 0:

CXFileEntity *the_entity = 0;
...


来源:https://stackoverflow.com/questions/4129261/c-breaks-on-class-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!