I know that constant variables outside classes can be optimized directly into function calls by the compiler, but is it legal for the compiler to do the same for constant class variables?
If there is a class declared like this:
class A {
public:
const int constVar;
//other, modifiable variables
A(int val): constVar(val) {
//code to initialize modifiable variables
}
};
and I create an instance of A and call a function like this:
A obj(-2);
int absoluteVal = std::abs(A.constVar);
is the compiler allowed to do this instead and make the class be sizeof(int)
smaller?:
A obj();
int absoluteVal = std::abs(-2);
The compiler is free to emit any code that preserves the "observable behavior" of the program (there is an exception with copy constructor which can be elided even if it has observable behavior, but it doesn't apply here). This is called the as if rule
any decent compiler will optimize the above to this:
As you can see, it doesn't have anything to do with constness (well, almost), just with observable behavior. You can try and play with the code adding in complexity and see how smart is the compiler in figuring out it can remove the code related to the class instance. Hint: it is very smart.
Is not clear to me what you mean by this:
I can tell you that: for a type
X
and an objectx
of such typesizeof(x)
is always= sizeof(X)
regardless of instantiations of the class. In other words the size of the class is determined when the class is defined, and as such it is not influenced by possible instantiations or lack of. The size of a class is the sum of all the sizes of its non-static data members plus padding. The padding is implementation defined and can be usually be somewhat controlled (e.g. packed structs). So no, the size of a class can never be smaller than the sum of the sizes all it's non-static non-reference data members.