Let’s start with the problem. I want to check whether a program received a text message that consists of four consecutive zeroes. Not
'0', but the numeric zero. I will create a constant
std::string representing the special sequence and compare the messages (also stored as
std::strings) I receive. I cannot just type:
const std::string Special = "\0\0\0\0";
As this would be interpreted, according to C rules, as a zero-length string. But there is another constructor exactly for our case, where I can say “character
C repeated N times”. So, I type:
const std::string Special ('\0', size_t(4));
I could have used braces for the initialization, but since I am aware of the
std::initializer_list gotchas (like the one described here), I am following my rule of thumb, “if you suspect the type might expose an initializer-list constructor, and you want to initialize through a different constructor, do not use braces”.
Now I can test my program. It still doesn’t work correctly for some reasons. It does not recognize the special messages as special, even though I would expect it to. I test and debug it for quite some time, until finally do I realize that my string
Special has a different value than I think. Continue reading
Compiler warnings are a very useful tool for detecting bugs in your program. Because you can enable them selectively, and because you can choose to turn them into hard errors on your compiler, you can in fact build a dialect, which is a safer subset of C++. You can enable even more warning if you assist your compiler a bit and instruct it about your intentions. We will see how to do it in one case. Continue reading
In this post I would like to discuss two issues brought up by the readers regarding previous posts on using
- Storing 0 in error codes, and using non-0 success values.
- Concerns about using globals.
In the previous posts we have seen what error codes and error conditions are. But the way we used them is far from optimum. In particular, the implementation of
FailureSourceCategory::equivalent was huge and error category
FailureSourceCategory was forced to be aware of all error codes from all sub-systems in the project. In this post we will see how we can do better, especially in more complex systems.
In the previous post we have seen how you can create your own error-code enumeration for representing different reasons for failure in your component, and how you can store them and convey them type erased via
std::error_code. In this post we will see how you can inspect an error situation encoded in
std::error_code, and how you can build useful queries about error conditions. Continue reading