I once competed with the STL, trying to create a container that is faster than the standard one. I wrote a class that writes when its constructor, copy constructor, and destructor is called. When reallocating and removing elements from the middle, vector <MyClass> generated a bunch of messages. In my array, I made it so that the constructor is called only when the element is added, and the destructor when it is deleted. Even with the redistribution of memory elements are not copied and not deleted.
This is how I achieved it. I allocated memory with the help of malloc and freed through free, which work with empty memory, and not with objects. I caused designers and destructors manually. With the redistribution of memory, I used realloc. No constructors and destructors are called. It turns out that the address of the object has simply changed (and if realloc could simply increase the buffer, it has not changed!). Compared to a vector, this introduces a small limitation: you cannot store objects in a container that rely on the fact that their address will always be the same. In any case, such objects are very rare, and in the vector there are already so many more important restrictions.
This approach can be applied here:
struct MyClass { double* ptr; //Ты забыл конструктор и деструктор MyClass() {Set();} ~MyClass() {Clear();} void Set() {ptr=new double[10000000];} void Clear() {delete[] ptr; ptr=nullptr;} };
In the main code:
MyClass* A=malloc(10000*sizeof(MyClass)); //Вызываем конструкторы for(int i=0; i<10000; i++) new(A+i) MyClass; //... //Работаем с ним до того, как перестанет хватать места //... A=realloc(A, 20000*sizeof(MyClass)); //Вызываем конструкторы для новых 10000 объектов for(int i=10000; i<20000; i++) new(A+i) MyClass; //... //Удаляем for(int i=0; i<20000; i++) a[i].~MyClass(); free(A);
Here is used placing new. If there is a compilation error, you may need to include the file new.h. MyClass simply plays the role of some kind of load, no matter what it does and how it allocates memory.