Tuesday, June 19, 2007

The Dangers of Copying

When I'm first learning a code base, I often make use of existing code, using it as an example to help speed things up. I don't do this blindly, of course -- that would probably result in many more problems than its worth. Still, it can be easy to fall into the trap of taking the example code as ground truth.

This happened to me yesterday while working on Inkscape. I'm adding new support for the SVG element <tref>. Because this element is similar in concept to <use> in that both refer to other elements, I have been looking at the code for <use> as my model.

I needed a class to represent the link between the <tref> object and what it refers to. The <use> element simply subclasses URIReference to accomplish this, so I made a new subclass for my purposes, initially just duplicating the <use> version. When I tried to build the code, I got a linker error telling me there was no virtual table defined for my new class.

Cursing and hair pulling may or may not have followed.

Finally, I looked up URIReference to see what it had to say about the matter. Lo and behold, the function being overridden had a slightly different signature. There was an extra const in the parameter list in the <use> version. Removing it from my class solved all my problems. Sigh...

Why the code compiles and links properly with the extra const in the <use> rendition of the subclass, but not in mine, I will never know. But let this be a reminder to be wary of the dangers of using existing code as your example. Look around elsewhere in the code base and remember to question everything.

0 comments:

Post a Comment

Comments are moderated - please be patient while I approve yours.

Note: Only a member of this blog may post a comment.