Re: Crash in virtual method call
Re: Crash in virtual method call
- Subject: Re: Crash in virtual method call
- From: Paul Walmsley <email@hidden>
- Date: Thu, 12 Jun 2008 18:25:10 +0100
Brady Duga wrote:
You should *never* be doing c-style casts of C++ objects, especially
when you have complex inheritance hierarchies. I am guessing that the
bug *does* exist under Windows, but just isn't showing up due to
variations in the compiler.
Indeed, C-style casts of C++ objects is evil and masks a number of
potentially serious bugs. I've experienced similar sorts of crashes
before in this kind of situation: you have classes Base and Derived,
then you want to pass a Derived object into a function that takes a Base* :
void UseBase(Base* base) {...}
void DoSomething(Derived* d) {
UseBase(d);
}
Only the call to UseBase() results in a compiler warning: "can't convert
to type Base", or similar. The developer wonders why, because he knows
d can be converted to a Base pointer, so he becomes a bit more forceful:
UseBase((Base*)d);
This stops the compiler from complaining, and all is great, or at least
it is until it crashes. The source of this problem is that the cpp file
doesn't include Derived.h, so it doesn't know that Derived is related to
Base. The cast then means 'reinterpret this data as a different type of
object' rather than 'walk the vtable to get the interface pointer to
Base', and you end up with bogus data in your Base* object. In this
example, #including Derived.h allows the original version to build, and
all is well.
So, check your code for occurrences of C-style casts and read item 2 of
Scott Meyer's excellent More Effective C++ ('Prefer C++ style casts').
Paul
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden