I'm still working on a space shooter engine. All entities need to be stored in the dynamic memory. I managed to force this by making the constructor private and by adding a static method which dynamically creates an object and returns a pointer. Edit: as LB says in the next post, I don't need to force this. But it is most likely that the user will want to make them dynamically and we still have the following problem. It means the user has to do this...
1 2 3 4
entity* player = entity::create();
(*player).setPosition(something);
(*player).act();
(*player).draw();
You get the point, having to dereference the pointer before each call becomes painful. So I thought about this... Instead of returning a pointer, I can return a reference. Then the code is much cleaner.
1 2 3 4 5 6 7 8 9
{
entity& test = entity::create();
// do stuff...
test.act();
// more stuff...
test.destroy(); // deletes the dynamic object
}
I put this code between brackets. That's because we must make sure the reference test doesn't exist after destroy is called, because destroy() makes it invalid. This is fully functional and won't cause any problem as long as the user doesn't forget to never call any method on a destroyed entity. But it's evil code. Would you risk it, or is there another way around?
All entities need to be stored in the dynamic memory. I managed to force this by making the constructor private and by adding a static method which dynamically creates an object and returns a pointer.
What? Why would you do this? There is no reason to try and 'force' the use of dynamic memory here - just use dynamic memory naturally.
It's true, it doesn't really matter if I allow non-dynamic creation or not. I could just leave the constructor public in case someone wants to create an entity for the duration of a function.
But I still have the same ugly syntax problem if the user just does entity* test = new entity(); which is going to be the most common situation. Every method call is going to require (*nameofpointer).nameofmethod();
This is what I'm trying to avoid. But I guess it's better to have ugly syntax then invalid references.
Facepalm. I used it a lot when creating containers, but I hadn't thought about using it on methods. Now that you mention it, this is exactly how SDL works. You declare your images dynamically and you call methods using the arrow operator.
Well, guess this means no more programming pas 11pm. Thanks and sorry for the loss of time :)
> I managed to force this by making the constructor private
> and by adding a static method which dynamically creates an object
> user doesn't forget to never call any method on a destroyed entity.
> But it's evil code. Would you risk it, or is there another way around?
Provide a wrapper which exposes simple value semantics. Something like this: