Build objects in the heap

Hello experts!!
Why I always see in the geant4 examples that the objects in the main() are built in the heap?
It’s not clear to me if this way is mandatory.
Thanks in advance.

Best, D

You need to be careful about this, and check both the documentation and possibly the .hh files directly. Much of the G4 core is more than 20 years old, and does things in a somewhat old-fashioned way.

Singletons (like the RunManager) are instantiated on the heap because they’re singletons, so the direct constructor is private.

The RunManager takes ownership of most of the objects which are registered into it. If you instantated them on the stack, and then passed them by address, you would get double delete errors at the end of the job.

1 Like