0

次の初期化リストで何が間違っているのかを理解するのに助けが必要です。「Room」クラスにデフォルトのコンストラクターがないデータメンバーオブジェクト「RoomResources」を初期化するために使用しています。

/* 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);
    }

これで正しくコンパイルされ、問題ないように思えますが、プログラムを起動するとクラッシュします。この初期化リストを使用せず、代わりにデフォルトのコンストラクターを使用して「RoomResources」オブジェクトを使用しようとしたため、この初期化リストが問題であることはわかっていますが、プログラムは正常に実行されています。

プログラムをデバッグすると、次のエラーが表示されます。 -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;
}
4

1 に答える 1

3

問題は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);
    }

PS: 他のすべてのメンバー変数には初期化リストを使用します

于 2014-07-20T14:27:47.683 に答える