I am currently writing a little textbase advendture game where I want to create all GameObjects
centrally so that I can use shallow copies of them later on to save some memory. The way I doing that now is creating a static
instance in an extra header file wich will than be deleted when the program terminates.
Here is a simplified example of what I'm doing right now:
#ifndef OBJECTS_H_
#define OBJECTS_H_
#include "GameObject.h"
#include <iostream>
static GameObject *apple = new GameObject("Apple", [] () { std::cout << "Delicous apple!" << std::endl; return true; });
void deleteAll()
{
delete apple;
}
#endif
main.cpp:
#include <iostream>
#include <vector>
#include "GameObject.h"
#include "Objects.h"
using namespace std;
int main()
{
std::vector<GameObject*> objects{apple, apple};
try
{
objects[0]->use();
objects[1]->use();
}
catch (const GameObjectException &goe)
{
cout << goe.what() << endl;
}
deleteAll();
}
Is there a more elegant way of achieving this?