about non-virtual destructors...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi guys,

I'm adding a flag to the makefile called -Wnon-virtual-dtors. This
flag will warn you if you try to create a class which has virtual
functions but a non-virtual destructor.

Non-virtual destructors are generated by default for all classes
unless you specify otherwise. The problem with having a non-virtual
destructor for a virtual class is that if that class is deleted
through a pointer-to-base, a memory leak will be created because the
derived constructor will not be called.

Example mistake:
class Base {
~Base() { cout << "~Base" << endl; }
virtual void foo() { }
};
class Derived : public Base {
~Derived() { cout << "~Derived" << endl; }
void foo() { }
int extra_stuff;
};
Base *b = new Derived;
delete b; // memory leak!

Another thing: please ***don't specify destructors in header files***.
This greatly increases compile times because gcc uses the location of
the destructor to determine where to put the vtable of a class. So all
the N places that include a header with inline destructors will
generate a vtable for all of those classes in the .o. Then the linker
must eliminate all but one of those later. Also remember that virtual
functions cannot be inlined anyway, so you will not gain any
efficiency by putting a virtual destructor in the header file.

Finally, consider the advice from Joshua Bloch in Effective Java:
prefer composition over inheritance. Rather than having something like
this:
class MyCallback {
virtual ~MyCallback();
virtual int handle_callback() = 0;
};

You can have something like this:
template <typename T>
class MyCallBack {
int handle_callback();
T user_data;
}

There are no vtables in the second example.

Colin
--
To unsubscribe from this list: send the line "unsubscribe ceph-devel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html


[Index of Archives]     [CEPH Users]     [Ceph Large]     [Information on CEPH]     [Linux BTRFS]     [Linux USB Devel]     [Video for Linux]     [Linux Audio Users]     [Yosemite News]     [Linux Kernel]     [Linux SCSI]
  Powered by Linux