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 *a
applies operatordelete
to a non-pointer expression*a
of typeA
. The only way this can be legal is when typeA
is implicitly convertible to some pointer type.In this case your class
A
is implicitly convertible toB *
, which is exactly what happens when you dodelete *a
.In other words, your
delete *a
is actually interpreted asIt is
B
youdelete
in your code, notA
. This is why the destructor ofB
is called.If you wanted to destroy the
A
object, you'd have to do(note, no
*
). That would not callB
's destructor.