Nickun Nickun - 1 month ago 6
C++ Question

c++ game engine design and objects going out of scope

I'm working on a small component based game engine in C++. Various components are added to an internal list of a gameobject object, to save some time I don't make a member variable of these components, only the game object is a member variable, like so:

void Initialize()
MeshComponent* meshRenderer = new MeshComponent(mesh, material);

The meshRenderer variable is being added to a component list in AddComponent(), but goes out of scope at the end of this function.

Later on (in the game's update/draw loops) this component is called and everything works, despite the object having gone out of scope during initialization.

Do I understand something wrong about scope, is it safe to use like this or is there another approach I should take (without having to make member variables of each of my components)?

Thanks for the help!


First of all, I suggest you to study C++ more before starting big projects like game engine.

What goes out of scope is the meshRenderer variable that is of type MeshComponent*, that is pointer to MeshComponent. What happens when pointer goes out of scope? Nothing at all. The memory was allocated on heap using the new operator and it will stay there until you deallocate it using delete operator.