Sample code
#include <iostream>
struct base {};
template<typename Type>
struct left : base {
Type value;
};
template<typename Type>
struct right : base {
Type value;
};
int main() {
std::cout << "sizeof left<base> = " << sizeof(left<base>) << std::endl;
std::cout << "sizeof left<right<base>> = " << sizeof(left<right<base>>) << std::endl;
std::cout << "sizeof left<right<left<right<left<base>>>>> = " << sizeof(left<right<left<right<left<base>>>>>) << std::endl;
}
Output
With GCC 4.6 is
sizeof left<base> = 2
sizeof left<right<base>> = 3
sizeof left<right<left<right<left<base>>>>> = 6
With clang 3.1
sizeof left<base> = 2
sizeof left<right<base>> = 3
sizeof left<right<left<right<left<base>>>>> = 6
With MSVC 2012
sizeof left<base> = 1
sizeof left<right<base>> = 1
sizeof left<right<left<right<left<base>>>>> = 1
So, question is, is it bug in GCC/clang, or is it implementation defined, or is it right output (quotes from standard, or explanations of such behaviour will be nice)
The relevant quote is 1.8 [intro.object] paragraph 6:
In your
right<T>andleft<T>object (why have to different class templates? One should have been enough) you each have a membervalue(of typeT). Each one needs to get its own unique address. Thus,is definitely wrong! There are 6 distinct objects:
valuesleft<right<left<right<left<base>>>>>and only the
left<right<left<right<left<base>>>>>and one of its subjects the (the firstvalueif I recall other rules) can share an address. That is, the size of the object needs to be at least 5. Since objects work best when aligned it seems to get padded to 6 bytes (which is odd; I’d expect it to be padded to a multiple of 4).Even size of
left<base>could’t be1: There are twobaseobjects involved already! One in the form of the base class oflef<base> and one in form of a member of this class. These twobase` objects need distinct addresses and, thus, the size needs to be at least 2.In any case, object sizes only have requirements how big they are at least. They don’t have any requirement that they shall not be bigger than something. This is considered a quality of implementation issue. Based on this, the only compiler being wrong (assuming the sizes quotes are, indeed, correct) is MSVC++. The other sizes may sometimes be slightly bigger than desired but this isn’t an error.