Search code examples
c++destructornew-operatorplacement-new

Destructor direct call in C++


Hence the code below.

class A
{
    int x;
public:
    A() {x = 3;}
};


int main()
{
    void* mem = operator new(sizeof(A));
    A* obj = static_cast<A*>(new(mem)(A));
    std::cout << obj->x << std::endl;
    obj->A::~A();
    std::cout << obj->x << std::endl;
}

My first question is: Why I can directly call the destructor of A; My second question is: Why the output is:

3
3

The the object obj is not deleted after the destructor call? The second 3 bothers me.


Solution

  • Why can I call the destructor?

    Because it is a public member function, and you can call public member functions.

    Why is the object not deleted?

    In your specific case, it still exists because A has a trivial destructor.

    If it had a non-trivial one, it would be deleted in the sense that you are not allowed to use it anymore. If you do anyways, you have undefined behavior.

    For a more detailed discussion on that read this.