Re: Virtual destructors and the C++ standard.
On Jun 10, 7:03 am, ggroups_st...@shic.co.uk wrote:
I was recently surprised about how a chunk of code compiled and
executed, which lead me to wonder what would be "correct" from a C++
standards perspective. (I don't need help to arrive at sensible code,
this is for academic interest only...)
--
#include <iostream>
using namespace std;
class A {
public:
A() { cerr << "CA"; }
virtual ~A() =0; };
class B : public A {
public:
B(bool a) { if (a) throw a; }
~B() { cerr << "DA"; } };
int main(int c,char *v[])
{
try { B b(c==1); } catch(bool x) { cerr << "catch" << endl; }
return 0;}
--
I'm interested to know:
* While this obviously compiles, is it complete - i.e. should it link?
It's undefined behavior, so technically, we can't say. In
practice, I can't imagine a system where it would link.
* Should the fact that A has a pure virtual destructor influence
whether or not B's destructor is called in the context of exception
'a'?
No. Pure virtual has no influence on anything here. By the
time we get into B's constructor, A has been fully constructed,
so its destructor must be called.
Typically, the compiler will not detect that the code after the
declaration of b is unreachable, nor that in fact, the complete
program will never call the destructor of B, and will generate a
call to A::~A in the destructor of B, which on most systems will
be sufficient to make the link fail unless there is a definition
somewhere.
* Have either of the above two questions different answers if one
looks from the perspective different C++ standards vintages?
No.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34