I’m wondering, for no other purpose than pure curiosity (because no one SHOULD EVER write code like this!) about how the behavior of RAII meshes with the use of goto (lovely idea isn’t it).
class Two
{
public:
~Two()
{
printf("2,");
}
};
class Ghost
{
public:
~Ghost()
{
printf(" BOO! ");
}
};
void foo()
{
{
Two t;
printf("1,");
goto JUMP;
}
Ghost g;
JUMP:
printf("3");
}
int main()
{
foo();
}
When running the following code in Visual Studio 2005 I get the following output.
1,2,3 BOO!
However I imagined, guessed, hoped that ‘BOO!’ wouldn’t actually appear as the Ghost should have never been instantiated (IMHO, because I don’t know the actual expected behavior of this code).
What’s up?
I just realized that if I instantiate an explicit constructor for Ghost the code doesn’t compile…
class Ghost
{
public:
Ghost()
{
printf(" HAHAHA! ");
}
~Ghost()
{
printf(" BOO! ");
}
};
Ah, the mystery …
The standard talks about this explicitly – with an example; 6.7/3 “Declaration statement” (emphasis added by me):
So it seems to me that MSVC’s behavior is not standards compliant –
Ghostis not a POD type, so the compiler should issue an error when the thegotostatement is coded to jump past it.A couple other compilers I tried (GCC and Digital Mars) issue errors. Comeau issues a warning (but in fairness, my build script for Comeau has it configured for high MSVC compatibility, so it might be following Microsoft’s lead intentionally).