返回指针会扰乱对象(访问冲突)

Returning a pointer messes up the object (access violation)

本文关键字:访问冲突 对象 指针 返回      更新时间:2023-10-16

我在摆弄assimp和C++,我写了一个简单的函数来从文件加载场景。然而,当我试图返回指针时,对象会被搞砸,如果我试图检索成员数据,就会发生访问冲突。这个片段应该演示这个案例:

const aiScene* ResManager::loadScene(const std::string& pFile)
{
    Assimp::Importer importer;
    const aiScene* scene = importer.ReadFile(pFile, aiProcessPreset_TargetRealtime_MaxQuality);
    if(!scene)
    {
        printf("%sn", importer.GetErrorString());
        return 0;
    }
    // If I break the debug here, 'scene' is valid
    return scene;
}
void ResManager::loadFromFile(const std::string& pFile)
{
    const aiScene* scn = loadScene(pFile);
    // If I break the debug here, 'scn' contains gibberish
}

我想我错过了一些关于指针和常量之类的重要内容。有什么想法吗?

当函数结束时,importer似乎会破坏,因此对象scene不再指向有效指针。我认为用动态分配importer

   Assimp::Importer *importer = new Assimp::Importer; 

应该做到这一点。

你应该稍后用摧毁这个物体

delete importer;