Will the compiler combine classes that are identical in structure?

I hope this is not a duplicate of the question itself, but the search terms are so ambiguous that I cannot think of anything better.

In any case, let's 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 point of view, they are the same, also the compiler considers them as a kind of typedef? Or will it generate two separate units of code?

I am curious because I would like to go beyond typedefs and make several type options to improve readability. I don't want unnecessary duplication, though ...

Hooray!

+4
source share
6 answers

This is a complete implementation.

For example, I can use CLang / LLVM to simultaneously display both points of view:

  • CLang is a C ++ interface, it uses two different types to resolve function calls, etc ... and treats them as completely different values.
  • LLVM is the optimizer backend, it still does not care about names, but only about the structural representation and, therefore, collapses them into one type ... or even completely removes the time definition if it is useless.

If the question is: does such a class introduce a class, overhead, then the answer is no , so write the classes you need.

Note. The same thing happens for functions, that is, the optimizer can combine function blocks that are identical in order to get more strict code, this is not a reason to copy / paste, although

+2
source

These are completely unrelated classes with respect to the compiler.

If these are just POD C-structs, it will not actually generate any real code for them. (Yes, there is a silent assignment operator and some other functions, but I doubt the code is really compiled for this, it just embeds them if used).

+2
source

Since the classes you use as samples are only relevant at compile time, there is nothing to duplicate or collapse. Runtime, member variables simply access as "value at offset N".

+2
source

This, of course, is very implementation specific.

Any internal collapse here will be completely internal to the compiler mechanism and will not affect the generated translated code.

I would suggest that this is very unlikely, as I can come up with any benefits and several ways in which this could significantly complicate the situation. However, I cannot provide any evidence.

+2
source

No. Because they are literally two different types. The compiler should treat them that way. Intellectual merging does not occur.

+1
source

No, they are not considered as typedefs, because they are different types and can, for example, be used to overload functions.

On the other hand, types do not have any code in them, so there is nothing to duplicate.

+1
source

Source: https://habr.com/ru/post/1342028/


All Articles