此源码参考编程珠玑附录C时空开销源码例一。改动在于用template代替Macro。
Measure 方法:连续new类型T十二次,查看系统为每一个对象分配的实际大小。
结论:在64位的机器上,如果类型大小小于等于4字节,则分配64字节的空间。如果类型大小大于4字节,则最低分配72字节,以后每多出8字节,就分配多8字节。
#include "stdafx.h"#includeusing namespace std;template void MEASURE() { cout << typeid(T).name() << "\t"; cout << sizeof(T) << "\t"; int lastp = 0; for (int i = 0; i < 11; i++) { T *p = new T; int thisp = (int) p; if (lastp != 0) cout << " " << thisp - lastp; lastp = thisp; } cout << "\n"; }template struct structii { char c[i]; };int main(){ cout << "Raw sizeof"; cout << "\nsizeof(char)=" << sizeof(char); cout << " sizeof(short)=" << sizeof(short); cout << " sizeof(int)=" << sizeof(int); cout << "\nsizeof(float)=" << sizeof(float); cout << " sizeof(struct *)=" << sizeof(structii<1> *); cout << " sizeof(long)=" << sizeof(long); cout << "\nsizeof(double)=" << sizeof(double); cout << "\n\nMEASURE\n"; MEASURE <1>>(); MEASURE <2>>(); MEASURE <3>>(); MEASURE <4>>(); MEASURE <5>>(); MEASURE <6>>(); MEASURE <7>>(); MEASURE <8>>(); MEASURE <9>>(); MEASURE <10>>(); MEASURE <11>>(); MEASURE <12>>(); MEASURE <13>>(); MEASURE <14>>(); MEASURE <15>>(); MEASURE <16>>(); MEASURE <17>>(); MEASURE <18>>(); MEASURE <19>>(); MEASURE <20>>(); MEASURE <21>>(); MEASURE <22>>(); MEASURE <23>>(); MEASURE <24>>(); MEASURE <25>>(); MEASURE <26>>(); MEASURE <27>>(); return 0;}
Raw sizeofsizeof(char)=1 sizeof(short)=2 sizeof(int)=4sizeof(float)=4 sizeof(struct *)=4 sizeof(long)=4sizeof(double)=8MEASUREstruct structii<1> 1 12904 -9184 9616 64 64 64 368 64 64 64struct structii<2> 2 64 64 64 64 64 64 64 64 64 64struct structii<3> 3 64 64 64 64 64 64 64 64 64 64struct structii<4> 4 64 64 64 64 64 64 64 64 64 64struct structii<5> 5 72 72 72 72 72 72 72 72 72 72struct structii<6> 6 72 72 72 72 72 72 72 72 72 72struct structii<7> 7 72 72 72 72 72 72 72 72 72 72struct structii<8> 8 72 72 72 72 72 72 72 72 72 72struct structii<9> 9 72 72 72 72 72 72 72 72 72 72struct structii<10> 10 72 72 72 72 72 72 72 72 72 72struct structii<11> 11 72 72 72 72 72 72 72 72 72 72struct structii<12> 12 72 72 72 72 72 72 72 72 72 72struct structii<13> 13 80 80 80 80 80 80 80 80 80 80struct structii<14> 14 80 80 80 80 80 80 80 80 80 80struct structii<15> 15 80 80 80 80 80 80 80 80 80 80struct structii<16> 16 80 80 80 80 80 80 80 80 80 80struct structii<17> 17 80 80 80 80 80 80 80 80 80 80struct structii<18> 18 80 80 80 80 80 80 80 80 80 80struct structii<19> 19 80 80 80 80 80 80 80 80 80 80struct structii<20> 20 80 80 80 80 80 80 80 80 80 80struct structii<21> 21 88 88 88 88 88 88 88 88 88 88struct structii<22> 22 88 88 88 88 88 88 88 88 88 88struct structii<23> 23 88 88 88 88 88 88 88 88 88 88struct structii<24> 24 88 88 88 88 88 88 88 88 88 88struct structii<25> 25 88 88 88 88 88 88 88 88 88 88struct structii<26> 26 88 88 88 88 88 88 88 88 88 88struct structii<27> 27 88 88 88 88 88 88 88 88 88 88