2

私はゲームを構築しており、スプライトと呼ばれるオブジェクトのベクトルを持っています。

struct Sprite
{
    SpriteType texture;     // The texture enumeration
    float x;                // The x position of the sprite
    float y;                // The y position of the sprite
    float xVel;             // The x velocity of the sprite
    float yVel;             // The y velocity of the sprite
    int imgBlockX;          // The x block in the image
    int imgBlockY;          // The y block in the image
    int numFrames;          // The number of frames in the sprite animation
    int curFrame;           // The current frame of animation
    int delay;              // The delay between frame switches
    int elapsed;            // The amount of time on this frame
    long lastTime;          // The last update time
    long curTime;           // The current update time
    bool loop;              // Does this animation loop?
    int lifespan;           // The max lifespan of the sprite
    int order;              // 0 for first 1 for last
    bool hasChildren;       // Is this a parent sprite?
    int maxSize;
    std::vector<SpriteChild> children;// The sprites that are linked to this one (die when this one dies)
};

下部にあるように、スプライトの子のベクター自体が含まれています。スプライト ベクターから要素を削除すると、spritechild ベクターでメモリ リークが発生しますか?それとも対処されますか?

ありがとう!

4

4 に答える 4

1

ベクターは Sprite 構造体のメンバーとして割り当てられるため ( 経由では割り当てられませんnew)、 が削除されると自動的にクリーンアップSpriteされます。

new経由でオブジェクトを作成すると、メモリ リークが発生しますdelete

于 2012-06-14T23:35:29.530 に答える
0

SpriteChild のデストラクタが適切に定義されていない場合にのみ、リークが発生します (つまり、SpriteChild のデストラクタは、動的に割り当てられたメモリを削除する必要があります)。

2 回削除すると、クラッシュする可能性があります。

ただし、new で正常に割り当てられたオブジェクトを削除するだけでは、メモリ リークが発生することはありません。

于 2012-06-15T00:03:19.007 に答える
0

スプライト ベクトルをどのように割り当てても、そこから要素を削除すると、childrenそのオブジェクトに固有のベクトルの割り当てが解除されます。BelieveSpriteChildは、ポインター型の typedef ではなく、構造体名です。

于 2012-06-14T23:37:39.357 に答える
0

手を汚さなければ大事にしSpriteChildます。コンストラクタで何かを割り当てる場合は、必ずデストラクタで解放してください。IIRCは、メンバーのデフォルトの可視性を持っていることstructと大差ありません。classpublic

于 2012-06-14T23:38:00.200 に答える