There'a a handful of situations that the C++ standard attributes as undefined behavior. For example if I allocate with new[]
, then try to free with delete
(not delete[]
) that's undefined behavior - anything can happen - it might work, it might crash nastily, it might corrupt something silently and plant a timed problem.
It's so problematic to explain this anything can happen part to newbies. They start "proving" that "this works" (because it really works on the C++ implementation they use) and ask "what could possibly be wrong with this"? What concise explanation could I give that would motivate them to just not write such code?
Tell them about standards and how tools are developed to comply with the standards. Anything outside the standard might or might not work, which is UB.
I'd explain that if they didn't write the code correctly, their next performance review would not be a happy one. That's sufficient "motivation" for most people.
C++ is not really a language for dilletantes, and simply listing out some rules and making them obey without question will make for some terrible programmers; most of the stupidest things I see people say are probably related to this kind of blind rules following/lawyering.
On the other hand if they know the destructors won't get called, and possibly some other problems, then they will take care to avoid it. And more importantly, have some chance to debug it if they ever do it by accident, and also to have some chance to realize how dangerous many of the features of C++ can be.
Since there's many things to worry about, no single course or book is ever going to make someone master C++ or probably even become that good with it.
Undefined means explicitly unreliable. Software should be reliable. You shouldn't have to say much else.
A frozen pond is a good example of an undefined walking surface. Just because you make it across once doesn't mean you should add the shortcut to your paper route, especially if you're planning for the four seasons.
Turn on malloc_debug and
delete
an array of objects with destructors.free
ing a pointer inside the block should fail. Call them all together and demonstrate this.You'll need to think of other examples to build your credibility until they understand that they are newbies and there's a lot to know about C++.
John Woods:
"Demons may fly out of your nose" simply must be part of the vocabulary of every programmer.
More to the point, talk about portability. Explain how programs frequently have to be ported to different OSes, let alone different compilers. In the real world, the ports are usually done by people other than the original programmers. Some of these ports are even to embedded devices, where there can be enormous costs of discovering that the compiler decided differently from your assumption.