C ++ engine design and objects that go out of scope

I am working on a small component of the game engine in C ++. Various components are added to the gameobject internal list to save some time. I do not make a member variable of these components, only the game object is a member variable, for example:

void Initialize()
{     
   MeshComponent* meshRenderer = new MeshComponent(mesh, material);
   m_GameObject.AddComponent(meshRenderer);
}

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

Later (in the update / drawing cycles of the game) this component is called and everything works, despite the fact that the object went out of scope during initialization.

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

Thanks for the help!

+4
source share
3 answers

First of all, I suggest you learn C ++ even before launching large projects, such as the game engine.

What goes out of scope is a variable meshRendererthat has a type MeshComponent*, that is, a pointer to MeshComponent. What happens when a pointer goes out of scope? Nothing. The memory has been allocated on the heap using the operator new, and it will remain there until you free it with the operator delete.

+1

( / ) , , .

, :

void Initialize()
{     
   MeshComponent* meshRenderer = new MeshComponent(mesh, material);
   m_GameObject.AddComponent(meshRenderer);
}

(meshRenderer), . , } , "", .

, .

"", (, ).


, ( - )?

. , C ++, .

. [ ++ 11]

, ( ) .

, , std::shared_ptr.

, ( ). , std::shared_ptr . , shared_ptr, , ( ).

+1

Later (in the update / drawing cycles of the game) this component is called and everything works, despite the fact that the object went out of scope during initialization.

This component does not go out of scope unless deleted is in another place.

0
source

Source: https://habr.com/ru/post/1653584/


All Articles