vendredi 30 décembre 2022

Is object can be destroyed when called the destructor explicitly?

Have a look at following code:

#include <iostream>
#include <memory>

class A
{
public:
    A()
    {
        std::cout << "A() \n";
    }

    ~A()
    {
        std::cout << "~A() \n";
    }

    int a = 100;
};

class B
{
public:
    B()
    {
        ptr.reset(new A());
        std::cout << "B() \n";
        std::cout << "pointer value" << ptr.get() << std::endl;
        std::cout << ptr->a << std::endl;
    }

    ~B()
    {
        std::cout << "~B() \n";
    }

    void print()
    {
        std::cout << "print() " << a << b << "\n";
        std::cout << "pointer value" << ptr.get() << std::endl;
        std::cout << ptr->a << std::endl;
    }
private:
    std::unique_ptr<A> ptr;
    int a = 10;
    int b = 5;
};

int main()
{
    std::unique_ptr<B> p1(new B());   
    p1->~B();
    p1->print();
    return 0;
}

the output result:

A()
B()
pointer value010ECB60
100
~B()
~A()
print() 105
pointer value010ECB60
-572662307
~B()
~A()

The Question is:

  1. When class B's destructor called, class A's destructor also called, and class A's member a = 100 has been destroyed, but class B's member a = 10; b = 5 still exist, and it's value not changed, so class B's destructor can't be seen as a function, since it called class A's destructor, how to explain this?
  2. When exit the main() function, the destructor of class B called second time automatically, and code breaks with the error code HEAP[Destructor.exe]: Invalid address specified to RtlValidateHeap( 00EA0000, 00EACE38 ), because class B's destructor called first time so object A has been destroyed, this will destroy it twice?

I add some print info to track workflow, but i still don't figure out how it worked when called the destructor explicitly.

Aucun commentaire:

Enregistrer un commentaire