Will an empty class be optimized

Let's 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 ....

Would an optimizing compiler (e.g. g++ ) simply consider foo() as a void function and skip the actual memory allocation for an empty object? This may not do, because even an empty class has a size of 1.

+6
source share
1 answer

This is an example of using gcc.godbolt.org , where you can see which assembler code is generated (I recommend that you click the colourize button to see which C ++ code corresponds to the assembler code). You can see that even with -O0 there is no code generated to place or copy the object. You can try other compilers and optimization levels. You can use #define to easily compare code between the returned class A and void .

+6
source

All Articles