I don't understand the complete context in which you want to use this (in particular, what is the role of struct MyErrno
, and what is StreamErrno
, since your operator<<
definition applies to a value of type sockaddr_in
which isn't used).
However, in general terms, this is not a safe way to use errno
, although it's a perfectly safe way to use strerror_r
.
The problem is that you are mostly likely using this in a context like this:
if ((something) != OK) {
std::cerr << "Something bad happened: "
<< (some value which causes your function to be called)
<< ...
}
That is, there will probably be some system call (outputting the string "Something bad happened") between the system call which failed, leaving a value in errno
, and the use of errno
in your function. Pretty well any system call can cause errno
to be set, even if the error is harmless; consequently, best practice is to grab the value of errno
immediately. This would be a good reason to use a custom type like MyError
:
struct MyError {
int error;
MyError(int err) : error(err) {}
};
std::ostream& operator<<(std::ostream& os, const MyError& e) {
// as with your function, but using `e.error` instead of `errno`
}
if ((something) != OK) {
MyError e(errno);
std::cerr << "Something bad happened: " << e
<< ...
}