开发者

std::vectors in classes

I'm building a c++ program, and I need to store an indefinite (i.e., dynamic) number of images within a class. I also have an indefinite number of sprite objects which can display those images. Right now I have something like this:

class Hud {
  std::vector<Image> images;
  std::vector<Sprite> sprites;
}

In order to avoid duplication of the images (thereby taking up excessive ram), I re-use them by putting a pointer to the image in the Sprite object.

Obviously, when an Image is added to the std::vector, these pointers are no longer any good. There's probably something wrong with my approach, but I'm not sure how to fix this. Rendering is being done in OpenGL. Any suggestions would be helpful.

How can I store a dynamic array of images that can be accessed开发者_如何学运维 by my sprite objects, and that will allow me to avoid duplicate images in memory (which can be extremely taxing for particle effects)? Alternate methods would be welcome, but I can't afford to spend more than a day or two rewriting my code.

Thanks.


You should be storing a list of shared_ptr, not a list of Image objects. That way, the list and Sprite classes can share ownership. Indeed, if you don't want the Sprite to actually own the image, they could store a weak_ptr instead of a shared_ptr. Though it's more likely that you would want the list itself to be a list of weak_ptr.

If you're not using a compiler with TR1 or C++11 support, then you can get these smart pointers from Boost.

Alternatively, you can use a std::list. That way, you can insert and remove from the list to your heart's content without invalidating pointers.


You can store pointers to the objects in your vectors, making sure to delete the objects before erasing them from the vector. Boost's shared pointer library might make this easier.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜