Hi,
This is a very convoluted problem I spent hours debugging to find that when I call std::vector<object>::push_back(Object()) destructor of previous Object is called.
Is this the behaviour of std::vectors or is something wrong with my code?
#include <iostream>
#include <vector>
class Manager;
class Entity
{
friend class Manager;
private:
int _mDisplayList; // for opengl, if it matters
public:
Entity():_mDisplayList(0){};
~Entity()
{
if(_mDisplayList)
{
_mDisplayList = 0;
}
}
void render()
{
std::cout << _mDisplayList << std::endl;
}
};
class Manager
{
private:
std::vector<Entity> _mEntities;
public:
Entity* createEntity()
{
// this line invokes ~Entity() of prev Entity();
_mEntities.push_back(Entity());
return &(_mEntities.back());
}
Entity* createEntity(int id)
{
Entity* ent = createEntity();
// generate some id for _mDisplayList
ent->_mDisplayList = id;
return ent;
}
};
void main()
{
Manager mgr;
Entity *ent1, ent2;
ent1 = mgr.createEntity(1);
ent2 = mgr.createEntity();
// expect output to be
// 1
// 0
ent1->render();
ent2->render();
// but turns out to be
// <garbage>
// 0
}