在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?

Is considring new keyword the elements inside the class that are initialized by the default constructor also with new keyword in C++?

本文关键字:new 关键字 C++ 是否 初始化 默认 构造函数 元素      更新时间:2023-10-16

初始化具有动态分配成员的类。 new 关键字是否用于分配整个内存块,同时考虑到将由默认构造函数在类内部初始化的成员?

我应该关心这些成员在内存中的放置位置(稀疏或放在一起(吗?我正在递归算法中使用巨大的顶点数组,该算法根据某些错误标准执行自适应网格细化。我需要遍历这些数组来执行其他操作,所以我需要性能。

此外,作为相关主题。下面用于在 main 函数中声明类的两种方法之一在性能方面是否首选?

你能推荐我一些关于这个主题的书/文章/网页吗?

总结问题的玩具代码示例:

class Octree {
vec3* Vertex;
vec3* Cell_Centers;
public:
Octree(unsigned population_to_allocate) //constructor
{
Vertex = new vec3[population_to_allocate*8];
Cell_Centers = new vec3[population_to_allocate];
}
int main()
{
unsigned population_to_allocate = 3000;
Octree* newOctree = new Octree(population_to_allocate);
Octree stackOctree(population_to_allocate);
}

鉴于您说过Octrees 的数量最多是 7 个,population_to_allocate是数千个,您可以做的最简单的有效方法是从vec3*更改为std::vector<vec3>。 然后你的构造函数将如下所示:

Octree(unsigned population_to_allocate) //constructor
: Vertex(population_to_allocate)
, Cell_Centers(population_to_allocate)
{
}

不使用new,您将轻松避免内存泄漏和错误。 没有理由使事情变得比这更复杂,因为您只有少数Octree实例。