C ++重载了new []查询:它用作参数的大小是多少? [英] C++ overloaded new[] query : What size does it take as parameter?

查看:85
本文介绍了C ++重载了new []查询:它用作参数的大小是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我像这样重载了运算符new []

void * human::operator new[] (unsigned long int count){
      cout << " calling new for array with size  = " << count <<  endl  ;
      void * temp = malloc(count) ;  
      return temp ; 
}

现在打电话

human * h = new human[14] ;

sizeof(human) = 16,但计算它打印的是232,即14 * 16 + sizeof(int *)= 224 + 8.

为什么要分配这个额外的空间?它将落在哪里? 因为当我打印*hh[0]时会得到相同的结果,所以它不在内存块的开头.完全正确吗?还是我在这里错过了一些东西?

解决方案

分配的额外空间用于存储数组的大小以供内部使用(实际上,delete[]知道要删除多少).

存储在内存范围的开始位置,紧接在之前 &h.要查看此内容,只需查看operator new[]temp的值.该值将与&h中的值不同.

I have overloadded operator new[] like this

void * human::operator new[] (unsigned long int count){
      cout << " calling new for array with size  = " << count <<  endl  ;
      void * temp = malloc(count) ;  
      return temp ; 
}

and now calling

human * h = new human[14] ;

say sizeof(human) = 16 , but count it prints is 232 which is 14*16 + sizeof( int * ) = 224+8 .

Why is this extra space being allocated ? And where does it fall in memory ? Because when I print *h OR h[0] I get same results , so its not in beginning of memory chunk. Is it correct at all OR I am missing some thing here ?

解决方案

The extra space allocated is used to store the size of the array for internal usage (in practice so that delete[] knows how much to delete).

It is stored at the beginning of the memory range, immediately before &h. To see this, just look at the value of temp inside your operator new[]. The value will differ from that in &h.

这篇关于C ++重载了new []查询:它用作参数的大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆