我正在制作一个SDL游戏,它使用libconfig从文件读取一些设置。问题是我创建了一个名为ClipList
的类,其中包含一个std::vector<SDL_Rect>
来存储设置,但是当尝试将SDL_Rect
对象添加到该向量时,出于某种原因,push_back什么都不做,最终得到一个空向量。C++ STD向量push_back似乎不工作
这是类:
class ClipList
{
public:
ClipList();
ClipList(int);
virtual ~ClipList();
void addClip(int,int,int,int);
void getClip(int,SDL_Rect*);
int getLength();
protected:
private:
std::vector<SDL_Rect> clips;
};
ClipList::ClipList(int l)
{
clips.reserve(l);
}
void ClipList::addClip(int x,int y,int w,int h){
SDL_Rect rect;
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
clips.push_back(rect);
}
void ClipList::getClip(int i,SDL_Rect* rect){
rect = &(clips.at(i));
}
int ClipList::getLength(){
return clips.size();
}
而这正是我初始化ClipList对象的功能。这个函数被main调用。
void set_clips(Config* placlips,ClipList* clips, ClipList* flipclips){
const Setting& root = placlips->getRoot();
int x,y,w,h;
try{
Setting& clipsett = root["clips"];
int cliplen = clipsett.getLength();
clips = new ClipList(cliplen);
flipclips = new ClipList(cliplen);
for(int i=0;i<cliplen;i++){
const Setting& c = clipsett[i];
if(!(c.lookupValue("x",x)&&c.lookupValue("y",y)&&c.lookupValue("w",w)&&c.lookupValue("h",h))){
continue;
}
clips->addClip(x,y,w,h);
}
}catch(const SettingNotFoundException &nfex){
cerr << "Setting not found at" << nfex.getPath() << endl;
}
}
不管ClipList
对象是否得到main
或set_clips
初始化,clips.push_back(rect)
不起作用。矢量的容量发生了变化,但是没有对象被存储,所以如果我试图对矢量做其他事情,甚至检查矢量是否为空,我最终会出现段错误。
是的,这是问题所在,虽然通过引用传递指针得到的代码来编译'SDL_Rect'对象仍然没有被存储在内存中。我通过初始化'main'中的ClipList对象并通过引用而不是指针传递ClipList对象来解决问题。 – Magnus
@Magnus这也是一个很好的解决方案。 –