c++ Vector.Push_Back impossible to use with textures?

Started by
2 comments, last by SiCrane 11 years, 6 months ago
I don't really know how to word this so I'll just draw it in psudo code...

[source lang="cpp"]class ROOMCLASS
{
a texture
a constructor that creates that texture with the directx device
a destructor that releases the texture
}

class HOUSECLASS
{
a vector of ROOMCLASS called "rooms";

constructor:
{
ROOMCLASS temp_room;
rooms.push_back(temp_room);
}
// at this point I have checked and the texture in both temp_room and rooms[0] are both valid.
} // at this point a ROOMCLASS destructor is called and releases that texture without issue.

HOUSECLASS houses;

function MAKE_A_NEW_HOUSE
{
HOUSECLASS temp_house;
// at this point the texture in temp_house.room[0] appears to be invalid.
houses.push_back(temp_house);
} // at this point a ROOMCLASS destructor is called and causes an error.[/source]

Is the problem that you can't use vector.push_back when a texture is involved?
Advertisement
No, push_back does what it says on the tin, regardless of types.

It's impossible to tell what's actually going on without some real code, but I would guess it would be to do with you breaking the rule of three.
N.B. this is the sequence of constructors/destructors going on. Seeing you've not written a copy constructor, the compiler is writing one for you, which isn't incrementing the texture's reference count as it should.

{
vector<Object> vec;
{
Object temp;//call temp.Object() -- constructor
vec.push_back(temp);//call vec[0].Object(temp) -- copy constructor
}//calls temp.~Object() -- destructor
};//calls vec[0].~Object() -- destructor
Your ROOMCLASS is not properly copyable.

A vector copies and owns each object as it is inserted into the vector. A new ROOMCLASS instance is created using the copy constructor and the old one is deleted.

vector requires copyable classes.

I expect that you wrote ROOMCLASS so that it properly destroys the texture when it is deleted. You need a system for copying the texture reference or creating a new texture reference in the new instance of ROOMCLASS.

shared_ptr is often referred to for this purpose. I consider shared_ptr a crutch. Each class should learn to manage it's own resources. In this case, perhaps a management class for textures that uses shared_ptr would be useful. I would avoid using shared_ptr as a requirement for using HOUSECLASS.

A vector copies and owns each object as it is inserted into the vector. A new ROOMCLASS instance is created using the copy constructor and the old one is deleted.

vector requires copyable classes.

This changes with a C++11 compiler. Objects placed in a vector in C++11 only need to be movable, not necessarily copyable. Either way copy/move semantics need to be implemented properly, but what is necessary changes depending on the semantics you plan to support.

This topic is closed to new replies.

Advertisement