Saturday, August 11, 2007

supporting the enforcement of namespaces

yesterday i was plagued by a terrible bug for a very long time. what was happening was this: i was using a class X* that was calling some third-party library that included a class Y*. i was calling a function in X that caused the destructor of Y to be called. whenever i called this function, i would get a seg fault occurring when the destructor of Y was called. some odd symptoms of this bug were that a string destructor was being called, but there were no strings anywhere, and i did not experience the bug when i took out certain linking dependencies.

when my host finally figured out what was going on, i had to laugh because it was so incredible. it turned out what had been going on was some dependency was bringing in another class Y had contained a string. when X called the destructor for its Y, the other destructor was being called, causing all sorts of problems. this should have been something caught by the linker, but for some reason it manifested itself as a runtime error.

lessons to be learned:

  • the linker does not always know best. trust nothing!
  • everything should be in a namespace. such problems could have been avoided if we had a n1::Y and a n2::Y.
  • C++ is a beautiful language with very good enforcement of abstraction barriers.

one of the above statements is not like the other.

*names have been changed to preserve anonymity.


Jean said...

this is apparently a problem with C++, the most beautiful language in the world.


JBruce said...

Is this with gcc? They have a pretty good user mailing list for sending test cases (the dev list is not for the faint of heart, so a test case should be sent to the user list for discussion, as the developers will reply to any flawed test quite harshly, even if the flaw was that you didn't read a 900-page standard). I haven't had any linker bugs on warninless "gcc -Wall" in a long time.

If its with VC++ on the other hand, well who knows.