Destructor
Destructor

Reputation: 14438

Why sizeof predefined stream objects varies from compiler to compiler?

Before you people start to mark this as duplicate, I've already read this. But it doesn't answer my question.

I agree that sizeof(int) is implementation defined behavior in C & C++. But I got surprised when I tested following program on various compilers.

#include <iostream>
using std::cout;
int main()
{
    cout << "Sizeof cout object: " << sizeof(cout) << '\n';
    cout << "Sizeof cin object: " << sizeof(std::cin) << '\n';
}

Output on g++ 4.8.1 & 4.9.2

Sizeof cout object: 140

Sizeof cin object: 144

Output on Visual Studio 2010

Sizeof cout object: 80

Sizeof cin object: 88

Output on online compiler (See live demo here)

Sizeof cout object: 272

Sizeof cin object: 280

My question is why it is implementation defined behavior? Why not having same size on all implementations of C++? Wouldn't it be if they have same size on all compilers? My friend told me that this decision is taken due to hardware & performance reasons. It would be very helpful If you explain the answer in depth at lowest level. How hardware plays role here? How performance can be gained by having different sized types on different implementations? Why there is so much difference in size for of cin & cout objects in the above program on various compilers?

Upvotes: 0

Views: 127

Answers (1)

TheUndeadFish
TheUndeadFish

Reputation: 8171

Because the different people who developed the different compilers decided to implement it in different ways.

Perhaps the differences could be due to choices of optimization or influenced by the underlying ways the platforms work. But it's hard to say more without doing an in depth analysis of the implementations themselves and the platforms they run on.

If you really want to know more, I think you'll have to actually dig into those implementations yourself and start asking about the specifics of them.

Upvotes: 3

Related Questions