Search code examples
c++constructordestructorplacement-new

Safe placement new & explicit destructor call


This is an example of my codes:

template <typename T> struct MyStruct {
    T object;
}

template <typename T> class MyClass {
    MyStruct<T>* structPool;
    size_t structCount;

    MyClass(size_t count) {
        this->structCount = count;
        this->structPool  = new MyStruct<T>[count];
        for( size_t i=0 ; i<count ; i++ ) {
            //placement new to call constructor
            new (&this->structPool[i].object) T(); 
        }
    }

    ~MyClass() {
        for( size_t i=0 ; i<this->structCount ; i++ ) {
            //explicit destructor call
            this->structPool[i].object.~T(); 
        }
        delete[] this->structPool;
    }
}

My question is, is this a safe way to do? Do I make some hidden mistake at some condition? Will it work for every type of object (POD and non-POD)?


Solution

  • No, because both your constructor and destructor are invoked twice. Because you have this:

    template <typename T> struct MyStruct {
        T object;
    }
    

    When you construct a MyStruct<T> the compile will construct the inner T and when you delete the object the inner T will have the destructor called automatically.

    For this example, there is no need for placement new or an explicit destructor call.

    Placement new would be useful if you allocate raw memory. For example, if you changed your new to:

    this->structPool  = new char[sizeof(T) * count];
    

    then you would want to placement new and explict destructor call.