Re: Future of C++
Razvan Cojocaru wrote:
For example, with C++ you need to remember to have a virtual
destructor for every class that you intend to ever use as a base
class, so that nasty things won't happen if you ever delete a
derived class object through a pointer to base class. Apparently
enough consensus has not been achieved in the standardization
committee for introducing the following common-sense rule of
thumb to C++0x: if a class has at least one virtual member
function, have the compiler magically make the destructor virtual.
Nonsense. First of all there is nothing wrong with having a non-
virtual *protected* destructor in a base class. Second introducing
such change will immediately break every Windows COM component ever
written.
Is it? How does a protected base class destructor solve the
following problem?
class Base {
public:
virtual perform() = 0;
protected:
~Base() {} // non-virtual destructor
};
class Derived : public Base {
public:
Derived() { rh_ = allocate_resource(); }
~Derived() { deallocate_resource(rh_); }
virtual perform() { /* implement me */ }
private:
// we're handling resources, careful with asignment
Derived(const Derived&);
Derived& operator=(const Derived&);
private:
resource_handle_t rh_;
};
int main()
{
std::auto_ptr<Base> pb(new Derived);
pb->perform();
// other code here...
}
When pb goes out of scope, it will only call Base::~Base(), thus
failing to deallocate the resource allocate by Derived's
constructor.
No, it doesn't. Because the Base destructor is protected, auto_ptr is
unable to call it, and the compiler will tell you so.
As usual, "C++ is a multi paradigm language", and not everyone uses
delete through pointer to base class. The compiler might very well
warn you that a virtual destructor is needed, but it shouldn't just
add one by itself.
Bo Persson
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]