You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将GLFW窗口封装为unique_ptr时为何触发访问违例?

静态库中GLFW窗口抽象为Window类后触发访问违例的解决方案

核心问题分析

你代码里的访问违例根源是构造函数中定义的m_Window是局部变量,而非Application类的成员变量:

  • 在Application::Application()里,std::unique_ptr<Window> m_Window;是构造函数内部的局部变量,构造函数执行完毕后这个变量会被销毁,对应的Window对象也会被释放。
  • 调用Application::init()时,你访问的m_Window要么是未初始化的类成员(如果类里声明了但没初始化),要么是不存在的变量,直接通过->访问必然触发访问违例。

修复步骤

1. 修正Application类的成员变量声明

在Application的头文件中,将std::unique_ptr<Window>声明为类的成员变量,而非在构造函数里定义局部变量:

#include <memory>
#include "Window/Window.h"

class Application {
private:
    std::unique_ptr<Window> m_Window; // 声明为成员变量
    Camera m_Camera; // 假设Camera是你的相机类
public:
    Application();
    bool init();
};

2. 正确初始化成员变量

修改Application的构造函数,用std::make_unique初始化成员变量m_Window,避免局部变量的干扰:

Application::Application() : m_Camera(1.0f, 1.0f, 1.0f, 1.0f),
                             m_Window(std::make_unique<Window>()) {
    // 无需再定义局部的m_Window
}

3. 修正Window::init()的逻辑错误

你的Window初始化代码存在逻辑错误:GLFW窗口提示必须在创建窗口之前设置,否则提示不会生效,可能导致OpenGL上下文版本不符合预期。同时,窗口创建失败时要记得终止GLFW:

bool Window::init() {
    if (!glfwInit()) {
        HZ_CORE_CRITICAL("GLFW FAILED");
        return false;
    }

    // 先设置窗口提示,再创建窗口
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    m_gWindow = glfwCreateWindow(800, 600, "ALAvery", NULL, NULL);
    if (!m_gWindow) {
        HZ_CORE_CRITICAL("GLFW WINDOW CREATION FAILED");
        glfwTerminate(); // 清理GLFW资源
        return false;
    }
    glfwMakeContextCurrent(m_gWindow);

    int status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
    HZ_CORE_ASSERT(status, "Failed to initialize Glad!");
    
    return true; // 确保返回初始化状态
}

内容的提问来源于stack exchange,提问作者Lynn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 05:34:53