Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 562
DarthRubik Avatar asked May 02 '16 20:05

DarthRubik


1 Answers

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.

like image 144
nwp Avatar answered Sep 21 '22 10:09

nwp