Vector of Textures

Started by
5 comments, last by Evil Steve 14 years, 1 month ago
Hi again, I'm trying to use a std::vector to store my textures (LPDIRECT3DTEXTURE9), and I'm having some problems. The vector is declared as vector<LPDIRECT3DTEXTURE9> mTextures; I've tried:

LPDIRECT3DTEXTURE9 temp;
D3DXCreateTextureFromFile(..., &temp);
mTextures.push_back(temp);
temp->Release();
and

mTextures.resize(mTextures.size() + 1);
D3DXCreateTextureFromFile(..., &mTextures[0]);
but when I try to draw using the texture at a later time in the game, the game crashes. Is there a way to use LPDIRECT3DTEXTURE9 with vectors? Thanks
Advertisement
With your first code example, you're releasing the texture as soon as you've created it.

With your second example, you're overwriting the first entry in the vector (leaking resources) and appending a NULL pointer on the end of the vector.

Try the first one without the Release in there, or the second one changed to:
mTextures.resize(mTextures.size() + 1);D3DXCreateTextureFromFile(..., &mTextures.back());
I would actually store a CComPtr<IDirect3DTexture9>'s in the vector, or if necessary CAdapt<CComPtr<IDirect3DTexture9>>'s, or other such smart pointer.

Then just use push_back as normal and not have to worry about the Releasing of the object when it's removed from the container.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms
Thanks guys, it worked.

I thought that when you push something onto a vector, it's really copied into it. Is that right? If it is, why does releasing the temp texture after pushing it onto the vector release the texture in the vector as well?
A vector is a container...it holds whatever you defined it to hold.

So for example

std::vector<Texture *> TextureList;

Would be a vector that "contains" pointers to a "Texture"

If you do the following...

Texture * texture1 = new Texture();

TextureList.push_back( texture1 );

texture1->Release();

or

delete texture1;

Then TextureList (the container) will still contain the pointer (but it will now not be valid, since you have either Released() it or deleted it...so don't try using it :)

I think that is correct.


Ok, that makes more sense now.

Thanks
Quote:Original post by Aiwendil
I thought that when you push something onto a vector, it's really copied into it. Is that right? If it is, why does releasing the temp texture after pushing it onto the vector release the texture in the vector as well?
Tes, that's right. But LPDIRECT3DTEXTURE9 is typedef'd as IDirect3DTexture9* - I.e. it's a pointer that's stored in the object, and the pointer that's copied - not the object being pointed at.

This topic is closed to new replies.

Advertisement