Created
November 16, 2017 20:58
-
-
Save FlyingJester/a88d092d92355cafa1ba903ddc521410 to your computer and use it in GitHub Desktop.
Exceptions help you write such safe code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <exception> | |
#include <stdexcept> | |
#include <vector> | |
#include <assert.h> | |
#include <stddef.h> | |
// Returns a munged/hash of an int. | |
// Always returns something different than what is passed in. | |
int munge(int i){ | |
// We can't munge zero, it would still be zero, so that's an exception! | |
if(i == 0) | |
throw std::runtime_error("You're screwed now."); | |
return (i >> 2) ^ (i << 7); | |
} | |
class frobulator{ | |
std::vector<int> m_data0, m_data1; | |
public: | |
void add(int i){ | |
// We always add to both the vectors at once, so it's safe! | |
m_data0.push_back(i); | |
m_data1.push_back(munge(i)); | |
// Munging should always return different data. | |
assert(m_data0.back() != m_data1.back()); | |
} | |
void dump(){ | |
// We know the vectors are the same size, so it's safe! | |
for(size_t i = 0; i < m_data0.size(); i++){ | |
printf("%i -> %i\n", m_data0[i], m_data1[i]); | |
} | |
} | |
}; | |
int main(int argc, char **argv){ | |
frobulator f; | |
for(size_t i = 0; i < 37; i++){ | |
try{ | |
f.add(i); | |
} | |
catch(...){ | |
} | |
} | |
// Watch the fireworks. Or maybe it's just a whimper. | |
f.dump(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment