Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a compiler collapse classes which are identical in their structure?

I hope this isn't a duplicate of a question itself, but the search terms are so ambiguous, I can't think of anything better.

Say we have two classes:

class FloatRect
{
 float x,y,width,height;
};

and somewhere else

class FloatBox
{
 float top,left,bottom,right;
};

From a practical standpoint, they're the same, so does the compiler treat them both as some sort of typedef?

Or will it produce two separate units of code?

I'm curious because I'd like to go beyond typedefs and make a few variants of a type to improve readability.

I don't want needless duplication, though...

like image 711
Erius Avatar asked Dec 29 '22 00:12

Erius


2 Answers

This is completely implementation specific.

For example I can use CLang / LLVM to illustrate both point of view at once:

  • CLang is the C++ front-end, it uses two distinct types to resolve function calls etc... and treats them as completely different values
  • LLVM is the optimizer backend, it doesn't care (yet) about names, but only structural representation, and will therefore collapse them in a single type... or even entirely remove the time definition if useless.

If the question is about: does introducing a similarly laid-out class creates overhead, then the answer is no, so write the classes that you need.

Note: the same happens for functions, ie the optimizer can merge blocks of functions that are identical to get tighter code, this is not a reason to copy/paste though

like image 198
Matthieu M. Avatar answered Dec 30 '22 15:12

Matthieu M.


They are totally unrelated classes with regards to the compiler.

If they are just POD C-structs, it won't actually generate any real code for them as such. (Yes there is a silent assignment operator and some other functions but I doubt there will be code actually compiled to do it, it will just inline them if they are used).

like image 20
CashCow Avatar answered Dec 30 '22 15:12

CashCow