我想知道为什么在下面的代码中指针aptr和amemTab之间的差异不等于分配数组的大小(10 * sizeof(A))而是64字节(sizeof(A)是4)。
在调试模式下:
aptr 0x00395e38
amemTab 0x00395e78
Win XP 家庭版,MSVS2010,x86 Intel 1.86
我想这与填充有关?(我没有删除基类和派生类的代码,因为我想准确地展示我正在测试的内容,但这里是多余的,我只说两行:
A * aptr=static_cast<A*>(amem);
void * amemTab= operator new[](10*sizeof(A));
我的完整示例:
// exercise
//
#include "stdafx.h"
#include <algorithm>
void func(const int &i){printf("%d\n",i);}
class A{
public:
int i;
};
class B{
public:
int i;
private:
int j;
};
class base{
public:
void f(void){printf("base f not virtual\n");}
virtual void g(void){printf("base g virtual\n");}
void h(void){printf("base h not virtual\n\n");}
int i_;
base():i_(123){}
base(int):i_(12345){}
};
class derived:public base{
public:
void f(void){printf("derived f not virtual\n");}
virtual void g(void){printf("derived g virtual\n");}
};
int _tmain(int argc, _TCHAR* argv[])
{
int ij;
A a;/*a.i is not initialized*/
A * aprimprim=new A;/*i is not initialized (but ctor has been called)*/
A aprim=A();/*aprim.i is 0 initialized as it is public variable
and A has only public part (A is POD type) and () is written*/
A * ap=new A();/*int is 0 initialized*/
B b;/*b.i is not initialized and b.j is not initialized*/
B bprim=B();/*bprim.i is not initialized and bprim.j is not initialized
as A has public AND also private part*/
B * bp=new B();/*ints are both 0 initialized*/
void * amem= operator new (sizeof(A));/*uninitialized memory, only allocate*/
A * aptr=static_cast<A*>(amem);//cast pointer to void to pointer to A
void * amemTab= operator new[](10*sizeof(A));/*uninitialized memory, only
allocate for 10 objects of A size*/
A * aptrtab=static_cast<A*>(amemTab);/*cast pointer to void to pointer to
A. now it is possible to iterate through
this area of indexed memory:*/
for(int i=0;i<10;i++){
new(&aptrtab[i])A();//initialize each A object
}
int s=sizeof(A);
/*------------------------------*/
int myarray[5];/*ints are uninitialized*/
*(1+myarray)=13;/*pointer addition is commutative*/
2[myarray]=4;/*subscript operator is commutative*/
std::for_each(myarray,myarray+5,func);
/*---------------*/
int *what_here=const_cast<int*>(myarray-6600);
printf("what_here: %d\n",*what_here);
return 0;
}