reinterpret_cast unreliable on windows?
I have fixed this windows-only bug, but I cannot fully understand how: https://bugs.launchpad.net/inkscape/+bug/169011 The problem was in this line: g_snprintf( b, len, "%s:%s;", key, css.gcharp() ); and gcharp is defined as: gchar const *gcharp() const { return reinterpret_cast<gchar const *>(ostr.str().c_str()); } The problem is that sometimes, rarely on some Windows systems and more frequently on others, gcharp() returned empty string for non-empty ostr. I replaced it with simply: g_snprintf( b, len, "%s:%s;", key, css.str().c_str() ); and the problem went away. Can anyone explain how this could happen? Is reinterpret_cast unreliable? Maybe we should eliminate it everywhere? -- bulia byak Inkscape. Draw Freely. http://www.inkscape.org
On Dec 16, 2007, at 6:36 PM, bulia byak wrote:
The problem is that sometimes, rarely on some Windows systems and more frequently on others, gcharp() returned empty string for non-empty ostr. I replaced it with simply:
g_snprintf( b, len, "%s:%s;", key, css.str().c_str() );
and the problem went away.
Can anyone explain how this could happen? Is reinterpret_cast unreliable? Maybe we should eliminate it everywhere?
In general it's not that reinterpret_cast<> is unreliable, as much as it's dangerous. However, in this case I don't think it is to blame. To begin with, reinterpret_cast<> should be the cast of last resort. Older c-style casts (with bare parenthesis) should be avoided, and replaced with a precise cast. Generally static_cast<> is the better first choice. Also... in this particular case I would say that the cast is not to blame. However... that particular reinterpret_cast<> could be replaced with static_cast<>, since the char type is supposedly the same. You might do a quick check to see how that plays out. However, your change there did *two* things, not just one. The function that had been called used (ostr.str().c_str()), but you don't have access to the ostr directly. Instead the "str()" method was used: std::string str() const { return ostr.str(); } Notice that there are no references in play there. That means that a *copy* of ostr's str() result is returned, not the base string itself. To verify that the cast was not to blame, I'd suggest trying this and seeing if the bug is still gone: g_snprintf( b, len, "%s:%s;", key, static_cast<gchar const*>(css.str ().c_str()) );
participants (2)
-
bulia byak -
Jon A. Cruz