C++ local variables and registers
c++
Solution
What you described in your code goes beyond copying of member variables into local variables to enable register placement. In essence, your question illustrates the difference between two approaches:
- Fully computing a result locally before writing it to member variables, vs.
- Writing intermediate results to member variables as you go through computations.
Your program follows approach #1. It is more robust than #2, because the object remains in a consistent state while the computation is performed.
Approach #1 may give the compiler more opportunities to optimize your code, too. However, this is a secondary effect; your object staying consistent during the computation is more important.
Problem
I often saw that compiler put local function variables in registers. And I have a question regarding this. If I use some class member variable (integral/pointer, etc...) heavily, does it make sense, to temporary copy it to local variable, work with it, and than copy result to class member? For example (fill one way ptr list): ``` struct MyClass{ struct ObjectHolder{ ObjectHolder* next_free; }; ObjectHolder *next_free = nullptr; void fill(){ ObjectHolder *copy_of_free = next_free ; // copy to register? for (int i = 0; i < capacity; ++i) { ObjectHolder &obj = array[i]; // build chain of pointers obj.next_free = copy_of_free; copy_of_free = &obj; } next_free = copy_of_free; // back to memory } } ```