#include <vector>
#include <memory>
using std::vector;
using std::unique_ptr;
using std::move;
/// gameobjec base class
class gameobject
{
public:
virtual ~gameobject() {};
};
/// player class
class player: public gameobject
{
public:
float* some_data;
player(int map_size)
{
some_data = new float[map_size];
}
~player()
{
delete[] some_data;
}
};
/// handler class
class handler
{
public:
vector<gameobject*> objects;
vector<unique_ptr<gameobject> > objects_auto;
void addobject(gameobject* object)
{
objects.push_back(object);
}
void addobject(unique_ptr<gameobject>& object)
{
objects_auto.push_back(move(object));
}
void add_raw_to_auto(gameobject* object)
{
objects_auto.push_back(unique_ptr<gameobject>(object));
}
~handler()
{
// objects behind raw pointers must be explicitly deleted
for(auto obj: objects)
delete obj;
// nothing needs to be done about unique_ptr containers
}
};
int main()
{
handler* hand = new handler();
for(int i=0; i<100; ++i)
{
// add raw pointer to a collection of raw pointers
gameobject* pla = new player(i);
hand->addobject(pla);
// add unique_ptr to a collection of unique_ptr
unique_ptr<gameobject> pla_auto(new player(i*2));
hand->addobject(pla_auto);
// add raw pointer to a collection of unique ptr
gameobject* pla_raw = new player(i);
hand->add_raw_to_auto(pla_raw);
}
delete hand;
}