Memory allocation for objects in arrays
这是我的代码[请注意,我注释了cstr和destructor]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #include <iostream> #include <stdlib.h> #include class MyIntClass { int _mymember; public: // MyIntClass(){} // ~MyIntClass(){} void *operator new(size_t size) { std::cout <<"new: Allocating" << size <<" bytes of memory" << std::endl; void *p = malloc(size); return p; } void operator delete(void *p) { std::cout <<"delete: Memory is freed again" << std::endl; free(p); } void *operator new[](size_t size) { std::cout <<"new: Allocating" << size <<" bytes of memory" << std::endl; void *p = malloc(size); return p; } void operator delete[](void *p) { std::cout <<"delete: Memory is freed again" << std::endl; free(p); } }; void line(){ std::cout <<"\ --------------------------------------------------\ " << std::endl; } int main() { line(); std::cout <<"Using new overloading and malloc\ We will create one object of MyIntClass that is supposed to be 4 bytes" << std::endl; MyIntClass *m1 = new MyIntClass(); line(); //I want to create an array of the MyIntClass of two objects std::cout <<"Now we create array of MyIntClass using header" << std::endl; std::array<MyIntClass, 2> z = {}; std::cout <<" The elements in the array z ="<< z.size() <<std::endl; std::cout <<"The memory allocated for array z =" << sizeof(z) << std::endl; line(); std::cout <<"\ Now we create array using new[] overloading and malloc" << std::endl; MyIntClass *i = new MyIntClass[2](); delete[] i; } |
现在结果如下:
Using new overloading and malloc
We will create one object of MyIntClass that is supposed to be 4 bytesnew: Allocating 4 bytes of
memoryNow we create array of MyIntClass using
header
The elements in the array z = 2
The memory allocated for array z = 8Now we create array using new[] overloading and malloc
new: Allocating 8 bytes of memory
对我来说,作为缺乏经验的C程序员,我认为每件事都按预期运行
现在,如果我取消注释构造函数,则会发生相同的结果
但是,当我取消注释析构函数时,会出现不同的结果
Now we create array using new[] overloading and malloc
new: Allocating 12 bytes of memory
所以我的问题是对此的解释是什么:
创建两个对象的数组,每个对象为4个字节,这两种方法都会导致使用
但是,当我们有一个对象的析构函数时,malloc将为这个2个元素的数组分配12个字节而不是8个字节。
我在SO上看到了这个问题,但没有解释我的案情
以下是我的编译器版本:
gcc version 8.2.0 (MinGW.org GCC-8.2.0-3)
额外分配内存的原因是,编译器需要知道数组中元素的数量,以便能够在调用