【发布时间】:2018-09-28 05:54:56
【问题描述】:
在C++中,每次使用new []或delete [],分别分配或释放多少次内存?我的问题更具体地说是在具有各自构造函数和析构函数的类上使用它们。
比如,上下面的课:
#include <iostream>
class Cell
{
public:
Cell() : _value(2)
{
std::cout << "Cell being made!\n";
}
~Cell()
{
std::cout << "Cell being freed!\n";
}
const int& getVal() const
{
return _value;
}
private:
int _value;
};
现在,假设需要一个该类类型的数组,并使用new[],如下所示
Cell* cells = new Cell[5];
当它在可执行文件或程序中运行时,我还看到打印到标准输出的以下内容:
Cell being made!
Cell being made!
Cell being made!
Cell being made!
Cell being made!
随后当delete[] 被cells 指针调用时,我看到了:
Cell being freed!
Cell being freed!
Cell being freed!
Cell being freed!
Cell being freed!
我的问题是,在每个构造函数调用中,内存大小是否等于分配的一个类实例?比如new Cell[5]会分配内存5次吗?或者它是否分配一次然后对构造函数进行 5 次调用作为函数调用?与delete[] 相同,是否在每次析构函数调用时释放?
【问题讨论】:
-
请注意,通常有两个分配级别,来自
new和来自操作系统。new被实现为子分配器是很常见的;它只向操作系统询问大内存块,并在程序需要更小的内存块时对其进行细分。
标签: c++ memory constructor allocation