Memory ownership model

hi,

unfortunately, in the g4 documentation i was unable to find any relevant references about the general philosophy on object memory ownership model. we namely have a large legacy code base written in many years by many authors with very different levels of c++ comprehension so that the code is full of "new"s but very scarsely populated with "delete"s. unlike a typical example of running setup once, firing the particles, and then basically exiting the program, we have to be able to run the whole cycle repeatedly, in a loop if necessary. this crates a lot of memory-leak warnings from address sanitizer and valgrind, but simply remembering all the created pointers and deleting them at the end also does not work.

is there some specific documentation about the general principles of ownership in g4? which functions/classes/methods take over the ownership and which do not? one would have thought this kind of information should be readily available with every function/method documented, but i could not find any trace of it. i am very surprised this is (a) not asked more frequently by users who want to avoid memory leaks and (b) that for such an important toolkit this is not some kind of a urgent priority.

i am sorry if this questions arise just because of my ignorance and this information is clearly available somewhere else. thanks in advance for pointing out the hidden place of information treasure.

best,
darko.

No, it’s a very good question/requirement! Yes, improving the memory management model and clarity has been on the todo list since the move to C++11/17, but it has not been a priority due to other requirements/support taking higher priority and limited FTE/funding. Some of the work would also require a major interface change, which we can do, but stability of interface, even across major versions, is often a high priority demand, especially from the major users of the toolkit where it’s a backbone of production.

The overall design/guidelines of the toolkit are covered in the Toolkit Developer’s Guide, but that may not cover things in the detail you required. We can of course add to this, and your input/requirements here would be welcome - probably a request to the Documentation Working Group and/or Examples if you think coding examples would help here as well.

If there are specific areas that you need information on, then I can take a look/advise directly, but in general the primary areas where you’ll see new without a matching delete (or where a unique_ptr would be obvious) are geometry and physics processes.

Here, the ownership is typically held by an underlying “Store” or “Table” object, e.g. G4LogicalVolumeStore. Registration of newd instances is handled done in the base class constructors. A similar pattern is used in a few other places, but these are the primary ones.

1 Like