vendredi 19 mars 2021

Faster way to initialize a dynamic array in C++11 [closed]

I was asked to implement a really simple class (using C++11 and pointers) whose constructor only has the following line of code :

this->pointer = new unsigned char[100000]();

All the dynamically allocated bytes should be initialized to 0 and after some basic profiling with Valgrind and KCachegrind I realized that the constructor above is the most expensive one time-wise. I think that :

this->pointer = new unsigned char[100000];

is not the way to go as it might lead to undefined behavior in the future and given the size of 100000 bytes I was wondering if there is a faster way to do this.

Update to clarify things :

The class I implemented call it A only has this one - line constructor and the rest of the program consists of the following :

class A {

private:

    unsigned char *pointer;

public:

    A(){ this->pointer = new unsigned char[100000](); };

};


#include <iostream>

using namespace std;

int main ()
{

  int size = 30000;
  A **head = new A *[3000];

  for (int i = 0; i < size; i++)
    head[i] = new A ();

  for (int i = 0; i < size; i++)
    delete head[i];

  delete[] head;

  return 0;
}

Aucun commentaire:

Enregistrer un commentaire