Skip to content

Commit bc8d172

Browse files
committed
Implement std::system_error.
Notice that std::system_error depends on std::string, which means that it cannot be nothrow-copyable. If it didn't have that pointless dependency, i.e. if it really just contained a std::error_code and nothing else, then it could have been trivially copyable! The rationale for making it so heavyweight is presumably that you're going to be throwing this object, i.e. not copying it (since a throw-expression will usually result in a move, not a copy, of the thrown object), and the cost of the memory allocation for std::string (if it is not SSO'ed) will be negligible compared to the cost of the throw itself.
1 parent e4466c2 commit bc8d172

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#pragma once
2+
3+
#include "scratch/bits/containers/string.h"
4+
#include "scratch/bits/error-code/error-code.h"
5+
#include "scratch/bits/stdexcept/stdexcept.h"
6+
7+
namespace scratch {
8+
9+
class system_error : public runtime_error {
10+
error_code m_code;
11+
string m_what;
12+
public:
13+
explicit system_error(error_code v) : m_code(v), m_what(v.to_string()) {}
14+
explicit system_error(error_code v, const string& prefix) : m_code(v), m_what(prefix + ": " + v.to_string()) {}
15+
explicit system_error(error_code v, const char *prefix) : m_code(v), m_what(prefix + (": " + v.to_string())) {}
16+
explicit system_error(int v, const error_category& cat) : m_code(v, cat), m_what(v.to_string()) {}
17+
explicit system_error(int v, const error_category& cat, const char *prefix) : m_code(v, cat), m_what(prefix + (": " + v.to_string())) {}
18+
explicit system_error(int v, const error_category& cat, string prefix) : m_code(v, cat), m_what(prefix + ": " + v.to_string()) {}
19+
20+
const error_code& code() const noexcept { return m_code; }
21+
const char* what() const noexcept { return m_what.c_str(); }
22+
};
23+
24+
} // namespace scratch

include/scratch/system_error

+1
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22

33
#include "bits/error-code/error-code.h"
44
#include "bits/error-code/system-category.h"
5+
#include "bits/stdexcept/system-error.h"

0 commit comments

Comments
 (0)