This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Request for a C++ warning for undefined behaviour


On Wed, 2003-08-13 at 10:50, Michael Matz wrote:
> Hi,
> 
> I spent a good amount of today while debugging some C++ program which
> conceptually was doing something similar to the below code, which
> segfaults, when run:
> ------ snip -----
> struct A {
>         A(A*) {}
>         virtual void g() {}
> };
> struct B : public A {
>         virtual A* f(A*);
>         B() : A(f(this)) {}
> };
> 
> A* B::f(A *x) { return dynamic_cast<B*>(x); }
> 
> int main()
> {
>   B b;
>   return 0;
> }
> ------ snap -----
> 
> Well, if one manages to cut the thing down to this size the problem
> becomes easy to see, but if I had have a warning my day would have been
> saved ;-) 

If you write that kind of code you deserve everything you get.
If you're stuck maintaining someone else's mess, I can only sympathise.

The error your example exhibits is not detectable in general
due to the flaw in the C++ type system.

It would be possible to check if, in a ctor-initialiser, a direct call
is made to a virtual function of the current class.

Unfortunately, it is possible to circumvent such a check in
any number of devious ways, for example by simply wrapping
the call in a non-virtual member.

Since you shouldn't be writing code anything remotely
like this in the first place, it hardly seems like it would be
worthwhile to provide a special case check here.



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]