I was getting ready to add a new feature which required a new member attribute variable. I went ahead and added a declaration for it in the class definition. Obviously this sounds like nerd glossolalia to normal humans so don’t worry about the details — just have a look at the shape and colors of this.

class Block {
        ....
        list<string> lines;
        int new_variable= 0; // Trying to add this new variable.

Just to make sure I didn’t make any dumb mistakes, I tried to compile it. It compiled fine. Luckily I tend to automatically run the program when it compiles cleanly. However at runtime I got this bizarre error.

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted

Uh huh. That’s super not helpful. I had no idea why it said this. Remember, I’m not even doing anything. I’m adding the simplest declaration possible to a class which works fine. That is frustrating but it then goes from annoying to completely insane. Desperately trying random things attempting to at least get a better error, I try the following (simply the two declarations switched in order).

class Block {
        ....
        int new_variable= 0;
        list<string> lines;

And then it works. Compiles and runs fine. I was under the impression that if the declarations had nothing to do with each other, their order was completely optional. Fun stuff.

Fortunately my programming style is to drop tons of runtime hints about what exactly is going on. I was able to put diagnostics on high alert until I could zero in on exactly where the program stopped working. When I found the line it was dying on, I knew what the problem must be. I was asking for the last item of a container and I suspected the container was empty (perhaps the error message’s "null"). Checking the official documentation, my suspicions were confirmed.

If the container is not empty, the function never throws exceptions (no-throw guarantee). Otherwise, it causes undefined behavior."

I’ll say!

bjarne.png