Search code examples
c++new-operatordefault-constructor

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


Initializing a class that has members dynamically allocated. Does new keyword to allocate the entire block of memory taking into account the members that will be also initialized inside the class by the default constructor?

Should I care about where these members are placed in memory (sparsed or put together)? I'm working with huge arrays of vertex in a recursive algorithm that performs adaptive mesh refinement based on some error criteria. And I need to traverse those arrays to do other operations so I need performance.

Also, as a related topic. Is one of the two ways used below to declare a class inside main function preferred in terms of performance?

Could you recommend me some book/article/webpage about this topics?

Example of a toy-code that summarizes the issue:

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);
}

Solution

  • Given that you've said the number of Octrees is at most seven and population_to_allocate is in the thousands, the simplest efficient thing you can do is to change from vec3* to std::vector<vec3>. Then your constructor will look like this:

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

    By not using new, you'll avoid memory leaks and errors easily. And there's no reason to complicate things more than this, because you only have a handful of Octree instances.