Search code examples
c++new-operatordelete-operatorplacement-new

Allocate vs construct an array of ints using operator new and placement new


Hello to understand more placement new, operator new, expression delete.. and separating the initialization from construction, I've tried this example:

int main(){

    int* p = static_cast<int*>(operator new[](10 * sizeof(int)));
    p = new(p)int[10];

    for(int i = 0; i != 10; ++i)
        p[i] = i * 7;

    for(int i = 0; i != 10; ++i)
        std::cout << p[i] << ", ";
    operator delete[](p);

}
  • I've compiled it and run it and it works fine and checked it using Valgrind for memory leaks and nothing bad is reported. So is it how separate initialization from allocation?

  • What I am not sure about is that I used operator delete to free memory of the dynamic array but didn't destroy it (there is no placement delete). So is there some bad thing in my code?


Solution

  • As you noted, there is no placement delete. When using placement new, you have to call destructors manually, eg:

    void* mem = operator new[](10 * sizeof(T));
    T* p = new(mem) T[10];
    ...
    for(int i = 0; i < 10; ++i)
        p[i].~T();
    operator delete[](mem);
    

    Where T is the desired element type.

    Calling destructors is not very important for POD types, like int, but it is important for non-POD types, like std::string, etc, to avoid leaks.