On 24.11.2011 10:20, Qi wrote:
> The full question:
> Any portable and standard way to detect the absence of virtual
> destructor in base class?
>
> Boost has some type traits for that, but they are intrinsic and rely
> on the compilers internal implementation.
>
> Here is some sample code,
>
> class A {
> // no virtual destructor
> };
>
> class B : public A {
> // some data here, whatever
> };
>
> A * a = new B;
> delete a;
>
> If B has virtual destructor, the behavior of "delete a" is UB. (I
> spent half an hour on this issue).
> If B has no virtual dtor, memory leak!
>
> So the ideal way is, whenever newing a B like that, a static assert
> failure or runtime failure is thrown to indicate A needs a virtual dtor.
>
> Is it possible?
> I doubt that, but it's quite annoying to debug that problem in case
> I forget to give A a virtual dtor.
>
> If it's impossible, any suggestion on how to avoid forgetting give
> base class a virtual dtor?
Why are you using a raw pointer?
Use `std::unique_ptr` or `std::shared_ptr`, or e.g. `boost::shared_ptr`.
These smart pointers remember the proper derived class destruction to
use, freeing you having to have a virtual destructor.
Cheers & hth.,
- Alf
|