Saturday, April 12, 2014

Safe-casting Pointers

You cannot safe-cast a pointer. This will fail:

ptr as TProject

You can only cast pointers the unsafe way:

TProject(ptr)

That is, unless you use this neat trick:

TObject(ptr) as TProject

This will also catch programming errors, specifically a pointer that doesn’t point to an object.

4 comments:

  1. Anonymous23:53

    "This will also catch programming errors, specifically a pointer that doesn’t point to an object."

    That's just nonsense. casting a pointer to an object will only work if the pointer is actually an object pointer.

    Try this:

    TObject(pointer(-1)) as TComponent

    ReplyDelete
  2. @Anonymous: isn't that what he said? It will catch pointers that don't point to objects.

    ReplyDelete
  3. Anonymous11:13

    The example I gave is the best case scenario because it "just" throws an access violation. In real life the outcome of a hard cast on an unknown pointer value will depend on whatever happens to be in memory at that location. It might be an object or it might be random noise that just happens to look like an object.

    This is really basic stuff. Hard casting removes the safety of strongly types language. Using the "as" operator on a hard cast will not bring that safety back.

    ReplyDelete
    Replies
    1. Actually, even if it was "random noise that looks like an object," this would almost certainly catch it. Randomness means it's not 100% certain, of course, but with the way the as-cast works, essentially traversing a linked list of VMTs until it finds one that matches, the odds against "random noise" actually finding a match before either hitting an access violation, a nil, or an infinite loop are astronomically low.

      Delete