Re: Why not reject the dynamic instantiation of a class with non-virtual destructor?
Bob Bell wrote:
On Jun 29, 1:27 pm, Thomas Maeder <mae...@glue.ch> wrote:
Bob Bell <bel...@pacbell.net> writes:
If anything, delete expressions applied on pointers to base
classes without virtual destructor should be considered erroneous.
I don't think so.
struct Base
{
~Base(); // non-virtual
};
void f(Base* p)
{
delete p;
}
How could the compiler possibly tell whether this is an error or
not?
Reliably it can't
That's the point.
unless Base is abstract. Another point for those who
say that base classes should always be abstract.
The problem is that the compiler also has to compile the code given
above. Even if there are classes derived from Base, that doesn't mean
f() is incorrect. Certainly, if p points to a derived class object,
there's an error. But given that Base is not abstract, p could point
to a Base object; if I always call f() with Base objects, then there's
no problem.
I agree with you that for the given example (with a concrete class), the
compiler should not warn.
However, for this example:
struct Base
{
~Base(); // non-virtual
virtual void foo() = 0;
};
void f(Base* p)
{
delete p;
}
I would consider it a good QoI if the compiler gives a warning.
The chances that p does NOT point to a derived class are close to 0.
Preferably, I would even like to see the warning at the definition of
Base.
I don't think I want the compiler generating an error message because
there's a chance the code is wrong -- especially if I know the code is
correct.
For me, that depends on how big the chance is that the code is wrong.
If that chance is over 99% (or possibly even 95%), then I prefer the
warning.
Bob
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]