C ++重载了new []查询:它用作参数的大小是多少? [英] C++ overloaded new[] query : What size does it take as parameter?
问题描述
我像这样重载了运算符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.
为什么要分配这个额外的空间?它将落在哪里?
因为当我打印*h
或h[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屋!