用c语言指针实现vector,C使用指针将对象添加到Vector中

2023-05-16

我有一个向量添加包含 SDL_Surface 指针作为数据成员的对象,这意味着我必须使用复制构造函数来实现指针的深层复制 . 该对象释放析构函数中的表面(指针),这就是问题发生的地方 . 当对象被添加到向量中时(通过按下按钮)程序崩溃但是当我从析构函数中取走 SDL_FreeSurface(surface) (内存泄漏)时,程序在我将对象添加到向量时不会崩溃 . 如何将对象正确添加到向量中?有些人可能认为问题在于析构函数试图删除悬空指针,但是在向量中创建对象时会发生错误 .

class Block{

public:

Block(int x, int y, MediaFunctions &M_Functions);

Block(const Block& source);

~Block();

private:

SDL_Surface *block_surface_names;

SDL_Surface *block_surface_hours;

SDL_Surface *block_names_detected;

SDL_Surface *block_hours_detected;

SDL_Rect block_rect_names;

SDL_Rect block_rect_hours;

};

Block::Block(int x, int y, MediaFunctions &M_Functions){

block_surface_names = M_Functions.LoadOptimizedImage("block_names.png");

block_surface_hours = M_Functions.LoadOptimizedImage("block_hours.png");

block_names_detected = M_Functions.LoadOptimizedImag("block_names_detected.png");

block_hours_detected = M_Functions.LoadOptimizedImag("block_hours_detected.png");

block_rect_names.x = x;

block_rect_names.y = y;

block_rect_names.w = block_surface_names -> w;

block_rect_names.h = block_surface_names -> h;

block_rect_hours.x = block_rect_names.x + block_rect_names.w;

block_rect_hours.y = block_rect_names.y;

block_rect_hours.w = block_surface_hours -> w;

block_rect_hours.h = block_surface_hours -> h;

}

//copy

Block::Block(const Block& source)

{

block_surface_names = source.block_surface_names;

block_surface_hours = source.block_surface_hours;

block_names_detected = source.block_names_detected;

block_hours_detected = source.block_hours_detected;

}

Block::~Block(){

//having this is necessary obviously- crashes program

//removing this causes the program not to crash

SDL_FreeSurface(block_surface_hours);

SDL_FreeSurface(block_surface_names);

SDL_FreeSurface(block_hours_detected);

SDL_FreeSurface(block_names_detected);

}

//where the object with SDL_FreeSurface() in the dtor is added to vector - crash!

void Control::HandleEvents(SDL_Event &event, MediaFunctions &M_Functions){

if(event.type == SDL_KEYDOWN){

if( event.key.keysym.sym == SDLK_a )

//append a block instance using copy constructor

BlockVector.push_back(Block (Block(100,100, M_Functions) ) );

}

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

用c语言指针实现vector,C使用指针将对象添加到Vector中 的相关文章

随机推荐