What is the purpose of this code change?

I am trying to understand the benefits of the consequences / side effects / a recent code change made by someone. This change is as follows:

Original

static List<type1> Data; 

Modified

 static List<type1> & getData (void) { static List<type1> * iList = new List<type1>; return * iList; } #define Data getData() 

What purpose can change have?

+6
source share
4 answers

The benefit of the revision that I see is the “initialization time” problem.

The old code initiated initialization before calling main() .

The new code does not start initialization until getData() is called; if the function is never called, you will never pay to initialize a variable that you have not used. The disadvantage is that every time the function is used, the initialization of the generated code is checked, and every time you need to access the data list, there is a function call.

+4
source

If you have a variable with a static duration, it is created when the application is initialized. When the application terminates, the object is destroyed. It is not possible to control the order in which various objects are created.

This change will make the object created when it is first used, and (since it is dynamically allocated) it will never be destroyed.

This may be good if other objects need these objects when they are destroyed.

Update

The source code accessed the object using the Data variable. The new code does not need to be changed in any way. When the code uses Data , it actually uses the Data macro, which will be expanded into getData() . This function will return a link to the actual (dynamically allocated object). In practice, the new code will work as a replacement for the old code, with the only noticeable difference being what I described in the original answer above.

+3
source

Postponing the construct until the first use of Data avoids the " static initialization fiasco order ."

Having made some guesses about your List , ... the default Data built is probably an empty list of type1 elements, so it probably does not run the risk of invoking the corresponding fiasco. But perhaps someone felt it was better to be safe than sorry.

+1
source

There are several reasons why this change was made:

0
source

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


All Articles