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

问题描述 投票:-1回答:1

初始化具有动态分配成员的类。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);
}
c++ new-operator default-constructor
1个回答
0
投票

鉴于您已经说过Octree的数量最多为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实例。

© www.soinside.com 2019 - 2024. All rights reserved.