ZisIsNotZis
ZisIsNotZis

Reputation: 1740

Will compiler optimize and reuse variable

For example if I have the following code:

int main(){
  myClass a(...);
  a.doSomething();
  if(...){
    myClass c(...);
    c.doSomething();
  }
}

Will usual compilers like gcc or clang optimize the using of these variables by finding out "a" will not be used anymore during it's lifetime and instead of reallocating space for "c", just use space of a? If that do not work for class, will that work for "traditional" type like double or size_t?

I'm trying to minimize the allocation cost of a frequently called function. But at somewhere inside the function I feel some old variables are already useless but new variables should not be called that name. Will compiler directly reuse variable for me or should I do something like

myClass a(...);
something(a);
if(...){
  #define c a
  c=myClass(...);
  something c;
  #undef c
}

Upvotes: 1

Views: 1212

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

Generally, the compiler is not allowed to reuse a until the end of its scope, which is the closing brace } at the end of the function. This feature (destroying objects at predictable time) enables making guards in C++, when destructor executes some special code*.

I'm trying to minimize the allocation cost of a frequently called function.

Since allocating automatic variables costs virtually nothing, the majority of the cost is in calling the constructor. This is not something that you could optimize away.

* If your object has trivial destructor, the compiler could reuse the memory. This would save you memory, not time.

Upvotes: 5

Alexey Guseynov
Alexey Guseynov

Reputation: 5304

These variables are allocated on a stack. Even if compiler does not reuse the space, this will not lead to any additional CPU instructions, only RAM. Allocation on stack is just adding number of allocated bytes to stack pointer. And usually it is done with one instruction by adding size of all variables that exist in the function. And in any case compiler will be smart enough to reuse CPU register where variable is allocated.

Note, that if your classes have destructor, then they must persist until the end of the block. So in this case memory for variable a will not be reused because it is needed at the end of the function. But compiler can still reuse registers used for it.

Upvotes: 0

Related Questions