Chinaunix首页 | 论坛 | 博客
  • 博客访问: 748229
  • 博文数量: 239
  • 博客积分: 60
  • 博客等级: 民兵
  • 技术积分: 1045
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-22 18:25
文章分类

全部博文(239)

文章存档

2019年(9)

2018年(64)

2017年(2)

2016年(26)

2015年(30)

2014年(41)

2013年(65)

2012年(2)

分类: C/C++

2014-01-26 14:51:13

    可以使用C的宏和C++模板加上数组,模拟sizeof操作符。如果有浮点数或者class中的private数值等,只能不觉明历了。
Example:

点击(此处)折叠或打开

  1. // implement_sizeof.cpp
  2. //
  3. #include <iostream>

  4. using namespace std;

  5. #define SIZEOF(x) ((char *)(&x+1) - (char *)(&x));

  6. template <typename T>
  7. unsigned long int SIZEOF_CPP(const T &v)
  8. {
  9.     return (char *)(&v+1) - (char *)(&v);
  10. }

  11. template <unsigned long int N >
  12. unsigned long int SIZEOF_CPP_SEC(char (*t)[N])
  13. {
  14.     return N;
  15. };

  16. template <typename T, unsigned long int N >
  17. unsigned long int SIZEOF_CPP_ARRAY(T (&t)[N])
  18. {
  19.     return N;
  20. };

  21. typedef struct _SizeofTest
  22. {
  23.     int _size1;
  24.     int _size2;
  25.     char _size3;
  26. }SizeofTest;

  27. int main(int argc, char* argv[])
  28. {
  29.     SizeofTest data = {0};
  30.     SizeofTest dataArray[10] = {0};
  31.     unsigned long int size_c = SIZEOF(data);
  32.     unsigned long int size_cpp = SIZEOF_CPP(data);
  33.     unsigned long int size_cpp_array = SIZEOF_CPP_ARRAY(dataArray);
  34.     cout<<"size_c ="<<size_c <<endl
  35.         <<"size_cpp ="<<size_cpp <<endl
  36.         <<"size_cpp_array ="<<size_cpp_array <<endl;

  37.     const int x = 63;
  38.     typedef int (*newDefine[x]);
  39.     typedef int newDefine_sec[x];
  40.     typedef int (*newDefine_third)[x];

  41.     int ** pp = new (int (*[x]));
  42.     int size_new = sizeof(newDefine);
  43.     int size_new_sec = sizeof(newDefine_sec);
  44.     int size_new_third = sizeof(newDefine_third);
  45.     cout<<"size_new =" <<size_new <<endl
  46.         <<"size_new_sec =" <<size_new_sec <<endl
  47.         <<"size_new_third ="<<size_new_third <<endl;

  48.     return 0;
  49. }

Result:

点击(此处)折叠或打开

  1. size_c =12
  2. size_cpp =12
  3. size_cpp_array =10
  4. size_new =252
  5. size_new_sec =252
  6. size_new_third =4
阅读(780) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~