Search code examples
c++coding-styledestructor

Is calling destructor manually always a sign of bad design?


I was thinking: they say if you're calling destructor manually - you're doing something wrong. But is it always the case? Are there any counter-examples? Situations where it is neccessary to call it manually or where it is hard/impossible/impractical to avoid it?


Solution

  • Calling the destructor manually is required if the object was constructed using an overloaded form of operator new(), except when using the "std::nothrow" overloads:

    T* t0 = new(std::nothrow) T();
    delete t0; // OK: std::nothrow overload
    
    void* buffer = malloc(sizeof(T));
    T* t1 = new(buffer) T();
    t1->~T(); // required: delete t1 would be wrong
    free(buffer);
    

    Outside managing memory on a rather low level as above calling destructors explicitly, however, is a sign of bad design. Probably, it is actually not just bad design but outright wrong (yes, using an explicit destructor followed by a copy constructor call in the assignment operator is a bad design and likely to be wrong).

    With C++ 2011 there is another reason to use explicit destructor calls: When using generalized unions, it is necessary to explicitly destroy the current object and create a new object using placement new when changing the type of the represented object. Also, when the union is destroyed, it is necessary to explicitly call the destructor of the current object if it requires destruction.