gpt4 book ai didi

c++ - 防止对象立即被销毁

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:26 25 4
gpt4 key购买 nike

我正在尝试创建一个类对象的单个实例,以便通过包含 header 并调用适当形式的 getInstance() 使任何其他需要它的类都可以访问该实例 方法。我试图通过遵循 here 所示的单例示例来完成此操作但出于某种原因,这个单个实例在创建后立即被销毁。

下面是头文件的拷贝,Window.h

#pragma once

#include <string>
#include <SDL.h>

class Window {

public:
static Window* getInstance();
static Window* getInstance(const std::string &title, int width, int height);
private:
Window(const std::string &title, int width, int height);
~Window();

bool init();

std::string _title;
int _width = 800;
int _height = 600;

SDL_Window *_window = nullptr;

static Window *_instance;
// static Window _solidInstance;
};

下面是源文件,Window.cpp,为了节省空间,删除了一些不相关的部分。

#include "Window.h"
#include <iostream>

Window* Window::instance = 0;
SDL_Renderer *Window::_renderer = nullptr;

Window::Window(const std::string &title, int width, int height) {
// Code that isn't relevant to this issue
std::cout << "Window constructor called\n";
}

Window::~Window() {
// Code that isn't relevant to this issue
std::cout << "Window destructor called\n";
}

Window* Window::getInstance() {
return _instance;
}

Window* Window::getInstance(const std::string &title, int width, int height) {
if (_instance == 0) {
std::cout << "Just before construction\n";
_instance = &Window(title, width, height);
std::cout << "Just after construction\n";
// _solidInstance = Window(title, width, height);
}
return _instance;
}

构建并运行此代码后,以下行将按此顺序打印到控制台:

Just before construction
Window constructor called
Window destructor called
Just after construction

这告诉我,我创建的 Window 实例在 getInstance() 甚至有机会返回之前就已经被销毁了。我不确定如何防止这种情况发生。我曾尝试使用 Window 的常规实例而不是指向一个实例(请参阅引用 soldInstance 的注释掉的代码行)但这只会给我链接器错误。

非常感谢任何帮助。

最佳答案

你的问题在这里:_instance = &Window(title, width, height);您正在获取一个临时窗口的地址,该窗口在离开作用域后会被销毁。

将其更改为:_instance = new Window(title, width, height);

但请务必在退出程序之前删除窗口!

一个更好的解决方案是在退出时自动删除窗口:

Window* Window::getInstance(const std::string &title, int width, int height) {
static Window window{title, width, height};
return &window;
}

关于c++ - 防止对象立即被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48266796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com