使用std::shared_ptr时无法读取内存

Unable to read memory while using std::shared_ptr

本文关键字:读取 内存 ptr std shared 使用      更新时间:2023-10-16

我有一个类,它有一个std::shared_ptr作为成员,稍后在函数中初始化。然而,我认为它工作不正常,因为当我调试它并检查shared_ptr对象的布局时,当我试图查看内部指针(shared_ptr指向的类)时,它会显示<Unable to read memory>

下面的前三个文件片段来自第二个项目引用的DLL项目。IGLSLProgram.h文件包含在第二个项目中,以便可以使用DLL中定义的导出类。


IGLSL程序.h(DLL中的接口)

class IGLSLProgram;
typedef IGLSLProgram *GLSLProgramHandle;
typedef shared_ptr<IGLSLProgram> IGLSLProgramPtr;
extern "C" COMMON_API GLSLProgramHandle APIENTRY getGLSLProgram();
class IGLSLProgram {
public:
    IGLSLProgram() {}
    ~IGLSLProgram() {}
    // ...
    virtual void release() = 0;
};

GLSLProgram.h(实现IGLSL程序)

#include "IGLSLProgram.h"
class GLSLProgram : public IGLSLProgram {
public:
    GLSLProgram() {}
    ~GLSLProgram() {}
    // ...
    void release();
};

GLSLProgram.cpp(定义GLSLProgram实现)

#include "GLSLProgram.h"
COMMON_API GLSLProgramHandle APIENTRY getGLSLProgram() {
    return new GLSLProgram;
}
// ...

Program.h(使用DLL的程序)

#include "CommonIProgram.h"
#include "CommonIGLSLProgram.h"
class Program : public IProgram {
protected:
    IGLSLProgramPtr shaderProgram;
public:
    Program() {}
    ~program() {}
    void createShaderProgram();
    // ...
};

Program.cpp(定义在Program.h中声明的类)

#include "Program.h"
#include "CommonIGLSLProgram.h"
// ...
void Program::createShaderProgram() {
    shaderProgram = IGLSLProgramPtr(getGLSLProgram(), mem_fn(&IGLSLProgram::release));
    // ...

}


当检查Program.cpp片段中的最后一行时,我发现shaderProgram具有以下布局:https://i.stack.imgur.com/VZrkF.jpg

如果能在这个问题上提供任何帮助,我们将不胜感激。

我通过使Program.h中的IGLSLProgram shaderProgram;为静态来解决问题。这对我来说很好,因为Program类无论如何都应该只有一个实例。


程序.h(已解决)

#include "CommonIProgram.h"
#include "CommonIGLSLProgram.h"
class Program : public IProgram {
protected:
    static IGLSLProgramPtr shaderProgram;
public:
    Program() {}
    ~program() {}
    void createShaderProgram();
    // ...
};

我不确定的是为什么这有帮助,以及为什么std::shared_ptr不能是类中的非静态成员。如果有人能解释这一点,我将不胜感激。