Friday, July 21, 2006

Undefined Behavior 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);
}

No comments:

Post a Comment