#include <string>
#include <cstdio>
int main() {
std::string s = "12345678";
std::printf("[%s]\n", s);
}
Here is an obvious typo of missing “.c_str()”. But VS2011 even with /Wall doesn’t emit any warnings, and the program works. If to compile this code in gcc, it says “warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘…’; call will abort at runtime” and the program crashes with “Illegal instruction”.
Did they really implement a trick in VS STL to make programs having such typo working just because this typo is very common?
UPDATE: The question is why it works in VS?
It works because one possible outcome of undefined behaviour is that the program does what you intend. You don’t need to look any further than this. Undefined behaviour is something that you simply avoid rather than trying to understand its manifestation in one particular compiler.