How to keep objects created inside other objects alive without using new?

123 views Asked by At

I am writing a game in C++, and I have come upon this design problem:

I have a base class called Entity for all my objects in the game. In order to use inheritance, I am storing the pointers in my octree. In my game, there are objects that will be created by other objects' methods. The problem is: where can I store the objects created this way so that it will stay for the duration of the game so that the pointers I store are valid?

I do not want to use new because I will create probably hundreds or even thousands of objects this way and I heard new is very slow.

The only way I have come up so far is to have a big vector that stores all these objects. The vector will probably be initialized with a huge size so that it won't have to resize itself and messes with my pointers. This seems rather dumb though.

2

There are 2 answers

0
skeller On BEST ANSWER

First: don't worry too much about performance. Adhere to some basic rules for that and you'll be fine:

  • avoid copies of big objects (pass by pointer or reference)
  • prefer vector over map and set when you have < 50 entries, or do not need ordering
  • have a look at what the std::algorithm library gives you - these functions are usually fast and tested

most important thing for your project is: think about structure and design

  • use clear interfaces
  • have single responsibility of objects
  • prefer composition over inheritance

as for your concrete problem: It's fine to have a "ObjectManager" class. as a first implementation a vector is fine, too, just hide that as a implementation detail so you can change it later on if the need arises.

0
Christophe On

One way of improving the new is to define custom allocators for your object, that take advantage of knowledge about your classes to write a better new than the standard one.

The good news is that you can write your code immediately using new and later create your custom allocator. So don't get lost in the dangers of premature optimization, which is, we all know:

Premature optimisation is the the root of all evil
-- Donald Knuth

If Entity is the base class for all objects, I suppose that you'll make heavy use of polymorphism. Unfortunately, you can't manage easily polymorphic objects in vectors (which would be the more convenient and safer way) because of the slicing issue. So pointer is ok in this case. Maybe you could consider shared_ptr to avoid memory leaks.

This being said, you may be interested in this article about Entity-Component-System pattern in games, and memory allocation.