July 21, 2006 Archives

2006-07-21

undefined bahaviour trap

Quote from www.boost.org:
The C++ Standard allows, in 5.3.5/5, pointers to incomplete class types to be deleted with a delete-expression. When the class has a non-trivial destructor, or a class-specific operator delete, the behavior is undefined. Some compilers issue a warning when an incomplete type is deleted, but unfortunately, not all do, and programmers sometimes ignore or disable warnings.
So, for instance, this snippet shows a hard to track bug if the compiler doesn't warn:
class A;

void foo(A* a)
{
    delete a;
}

class A {
public:
    ~A() { }
};

int main()
{
    A* a = new A();
    foo(a);
}

Posted by Alexander Bernauer | Permanent Link | Categories: C++

2006-07-21

abstract destructor needs implementation

A pure virtual - or abstract - destructor needs an implementation in C++. For example this program does not link because of "undefined reference to A::~A".

class A {
public:
    virtual ~A() =0;
};

class B : public A { };

int main()
{
    B b;
}
This contradicts the definition of abstract functions. As on the one hand there is no other way to make a class whithout methods abstract and on the other hand a destructor must always be available there is no way out.

As far as I can see this is the consequence of Stroustrup's decision to not introduce too much new key words in order to not brake too much old C code.

Seen on "Scott Meyers, Effective C++, Item 14".


Posted by Alexander Bernauer | Permanent Link | Categories: C++