From §5.3.5[expr.delete]/1, I can understand that the destructor for the object *a is not invoked in the snippet below. But I didn't understand why is the destructor for the class member B invoked in this case, as can be seen in this live example.
#include <iostream>
class A
{
public:
class B{ public: ~B(){ std::cout << "B dtor" << '\n'; } };
A() { p = new B(); }
operator B*() { return p; }
private:
B* p;
};
int main()
{
A* a = new A();
delete *a;
std::cout << "end" << '\n';
}
Would appreciate some quote from the Standard explaining this.
Your
delete *aapplies operatordeleteto a non-pointer expression*aof typeA. The only way this can be legal is when typeAis implicitly convertible to some pointer type.In this case your class
Ais implicitly convertible toB *, which is exactly what happens when you dodelete *a.In other words, your
delete *ais actually interpreted asIt is
Byoudeletein your code, notA. This is why the destructor ofBis called.If you wanted to destroy the
Aobject, you'd have to do(note, no
*). That would not callB's destructor.