F
frs
For memory economization, I need to get rid if the virtual
destructor. Under this constraint I get caught up in a design,
where I need to call a destructor of a derived class from a
base class. Briefly it could be displayed like the code below.
It ends up deleting the member 'x' of 'B' twice. Why? Is there
a way around?
Thanks
Frank
=====================================================================
#include<iostream>
using namespace std;
struct TypeX { ~TypeX() { cerr << "destructed\n"; }
struct A { ~A(); }
struct B : public A {
TypeX x;
~B();
}
A::~A() {
// at this point, ~A knows, that 'this' points is in fact to a 'B'
// (it does! no need to say 'type-switches are bad' - there's no
other way)
delete &(static_cast<B*>(this)->x);
}
int
main(int, char**)
{
A* a = new B;
cerr << "before\n";
// somewhere, there might be someone deleting 'a'
delete a;
cerr << "after\n";
}
destructor. Under this constraint I get caught up in a design,
where I need to call a destructor of a derived class from a
base class. Briefly it could be displayed like the code below.
It ends up deleting the member 'x' of 'B' twice. Why? Is there
a way around?
Thanks
Frank
=====================================================================
#include<iostream>
using namespace std;
struct TypeX { ~TypeX() { cerr << "destructed\n"; }
struct A { ~A(); }
struct B : public A {
TypeX x;
~B();
}
A::~A() {
// at this point, ~A knows, that 'this' points is in fact to a 'B'
// (it does! no need to say 'type-switches are bad' - there's no
other way)
delete &(static_cast<B*>(this)->x);
}
int
main(int, char**)
{
A* a = new B;
cerr << "before\n";
// somewhere, there might be someone deleting 'a'
delete a;
cerr << "after\n";
}