C++:无法在初始化列表中找到错误编译正常但在启动时导致崩溃

标签 c++ initialization-list

我需要帮助来理解我在以下初始化列表中做错了什么。我正在使用它来初始化一个数据成员对象“RoomResources”,它在我的“Room”类中没有默认构造函数:

/* Public methods */
public:

//Constructor - Initialization list with all data member objects that doesn't have a default constructor
Room(const AppDependencies* MainDependencies, RoomId room_id, int width, int height, int disp_width, int disp_height) :

    RoomResources(this->GetAppRenderer())

    {
        //Store the provided initialization data
        this->MainDependencies = MainDependencies;
        this->room_id = room_id;
        this->width = width;
        this->height = height;
        this->disp_width = disp_width;
        this->disp_height = disp_height;

        //Set instance count
        this->instance_count = 0;

        //Load corresponding room resources
        this->Load(room_id);
    }

现在编译正确,对我来说似乎没问题,但是当我启动我的程序时它会导致崩溃。我知道这个 Init List 是问题所在,因为我尝试不使用它并使用“RoomResources”对象代替默认构造函数,并且我的程序运行良好。

当我调试我的程序时,出现以下错误: “在“e:\p\giaw\src\pkg\mingwrt-4.0.3-1-mingw32-src\bld/../mingwrt-4.0.3-1-mingw32-src/找不到源文件src/libcrt/crt/main.c""

似乎某个对象正在尝试调用程序中尚不可用的某些代码或数据,但我在我的代码中看不到问题。非常感谢您的宝贵时间。

编辑: 这是我的 GetAppRenderer 方法的定义:

const SDL_Renderer* Room::GetAppRenderer() {

//Return the const pointer to the App's SDL_Renderer object found in the AppDependencies data member
return this->MainDependencies->MainRenderer;
}

最佳答案

您的问题是 MainDependencies 尚未初始化(因为初始化列表在主构造函数的主体之前执行)所以当您调用 GetAppRenderer ()MainDependencies 仍然指向垃圾数据,您会崩溃。

你可以这样解决你的问题:

Room(const AppDependencies* MainDependencies, RoomId room_id, int width, int height, int disp_width, int disp_height) :
    // Order is important (GetAppRenderer needs MainDependencies to be initialized)
    MainDependencies(MainDependencies), RoomResources(this->GetAppRenderer())

    {
        //Store the provided initialization data
        this->room_id = room_id;
        this->width = width;
        this->height = height;
        this->disp_width = disp_width;
        this->disp_height = disp_height;

        //Set instance count
        this->instance_count = 0;

        //Load corresponding room resources
        this->Load(room_id);
    }

P.S: 我会为所有其他成员变量使用初始化列表

关于C++:无法在初始化列表中找到错误编译正常但在启动时导致崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24851316/

相关文章:

c++ - 初始化列表的好处

c++ - 对于按值传递的重成员,构造函数的初始化列表中真的需要 std::move 吗?

c++ - 纯虚函数

C++将不同的模板化对象存储到同一容器中的任何方式

c# - 这两个 List 初始化是否相同?

C++ 构造函数初始化

c++ - 如果成员是模板类,则在初始化列表中初始化某个类的成员

python - 从图像中获取两个图像,图像中有两个图像粘贴在一个文档中 - Python/C++

c++ - 插入排序怎么写

c++ - 使用命名空间和文件夹来组织代码是否太过分了?