gpt4 book ai didi

arrays - 内存中的数组布局

转载 作者:行者123 更新时间:2023-12-04 05:23:17 25 4
gpt4 key购买 nike

我想知道为什么在下面的代码中指针之间的区别
aptr 和 amemTab 不等于分配数组的大小(10*sizeof(A))而是 64 个字节(sizeof(A) 为 4)。

在 Debug模式下:

aptr 0x00395e38

amemTab 0x00395e78

Win XP Home Edition,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;
}

最佳答案

严格来说,两个连续的堆分配返回的指针之间的关系无法确定。分配器从两个完全不同的内存区域返回指针并不是不可想象的(例如,它可以根据请求的字节数使用不同的子堆)。

在您的情况下可能发生的是:

  • 您的分配器以大于 1 个字节的块管理内存;
  • 分配器使用与已分配内存相邻的几个字节作为其内部数据结构。

  • 这两者都会产生开销。

    此外,内存分配必须满足某些对齐要求。这通常会导致进一步的开销。

    关于arrays - 内存中的数组布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13482611/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com