samedi, mars 17, 2007

Comment faire planter un programme en C++ rapidement et efficacement:

std::string MyString(false);

Radical. Sous MSVC, c'est le crash immédiat, tandis que gcc lève une exception. Et j'ai poursuivi ce maudit bug pendant 1 heure vendredi. Ce n'était pas aussi évident que cette bête ligne: l'horreur était planquée dans 2 couches de templates.

Histoire d'ajouter à la bizarrerie, on remarquera que la même chose avec un "true" à la place du "false" revoie une belle erreur de compilation. L'explication étant, je suppose, que "false" est casté en 0, lequel est casté en pointeur nul, lequel est accepté par le constructeur de std::string, tandis que true est casté en 1, lequel ne peut pas se caster implicitement en pointeur. Et nous sommes sauf!

Grrr!


How to crash a C++ program quickly and efficiently:
std::string MyString(false);

Under MSVC, it's an immediate crash, while gcc raises an exception. And it took one hour for me to debug the thing, last Friday. Of course, it was not as obvious as this single line, as it was buried through 2 layers of templates.

So that the thing looks even stranger, the same thing with a "true" in place of the "false" will actually raise a nice compilation error. The explanation is, I suppose, that "false" is casted as 0, then casted as the null pointer, taken by the constructor of std::string. On the other hand, "true" will be casted as 1, and there will be no implicit casting in a pointer. We're safe!

Grrrr!

Aucun commentaire: