可以使用C的宏和C++模板加上数组,模拟sizeof操作符。如果有浮点数或者class中的private数值等,只能不觉明历了。
Example:
-
// implement_sizeof.cpp
-
//
-
#include <iostream>
-
-
using namespace std;
-
-
#define SIZEOF(x) ((char *)(&x+1) - (char *)(&x));
-
-
template <typename T>
-
unsigned long int SIZEOF_CPP(const T &v)
-
{
-
return (char *)(&v+1) - (char *)(&v);
-
}
-
-
template <unsigned long int N >
-
unsigned long int SIZEOF_CPP_SEC(char (*t)[N])
-
{
-
return N;
-
};
-
-
template <typename T, unsigned long int N >
-
unsigned long int SIZEOF_CPP_ARRAY(T (&t)[N])
-
{
-
return N;
-
};
-
-
typedef struct _SizeofTest
-
{
-
int _size1;
-
int _size2;
-
char _size3;
-
}SizeofTest;
-
-
int main(int argc, char* argv[])
-
{
-
SizeofTest data = {0};
-
SizeofTest dataArray[10] = {0};
-
unsigned long int size_c = SIZEOF(data);
-
unsigned long int size_cpp = SIZEOF_CPP(data);
-
unsigned long int size_cpp_array = SIZEOF_CPP_ARRAY(dataArray);
-
cout<<"size_c ="<<size_c <<endl
-
<<"size_cpp ="<<size_cpp <<endl
-
<<"size_cpp_array ="<<size_cpp_array <<endl;
-
-
const int x = 63;
-
typedef int (*newDefine[x]);
-
typedef int newDefine_sec[x];
-
typedef int (*newDefine_third)[x];
-
-
int ** pp = new (int (*[x]));
-
int size_new = sizeof(newDefine);
-
int size_new_sec = sizeof(newDefine_sec);
-
int size_new_third = sizeof(newDefine_third);
-
cout<<"size_new =" <<size_new <<endl
-
<<"size_new_sec =" <<size_new_sec <<endl
-
<<"size_new_third ="<<size_new_third <<endl;
-
-
return 0;
-
}
Result:
-
size_c =12
-
size_cpp =12
-
size_cpp_array =10
-
size_new =252
-
size_new_sec =252
-
size_new_third =4
阅读(821) | 评论(0) | 转发(0) |