DarthRubik
DarthRubik

Reputation: 3985

Will an empty class be optimized away

Say I have the following class:

class A{ };

And then in my code I have a function:

A foo(){
  A ret;
  //Do stuff
  return ret;
}

And then I use the function later....

Will an optimizing compiler (like g++) just treat foo() like a void function and skip actually allocating memory for the empty object? It might not do this because even an empty class has a size of 1.

Upvotes: 6

Views: 279

Answers (1)

nwp
nwp

Reputation: 10001

This is a use case for gcc.godbolt.org where you can see what assembler code is generated (I recommend you click the colourize button to see which C++ code corresponds to which assembler code). You can see that even with -O0 there is no code generated to allocate or copy the object. You can try with other compilers and optimization levels. You can use #defines to easily compare the code between returning class A and void.

Upvotes: 7

Related Questions