test(util/exception): experiment with exceptions with nested std::function
Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
parent
737fe6830f
commit
3c8ccdd33d
1 changed files with 42 additions and 0 deletions
|
@ -5,6 +5,7 @@ Released under Apache 2.0 license as described in the file LICENSE.
|
|||
Author: Leonardo de Moura
|
||||
*/
|
||||
#include <string>
|
||||
#include <functional>
|
||||
#include "util/test.h"
|
||||
#include "util/exception.h"
|
||||
#include "util/sstream.h"
|
||||
|
@ -42,10 +43,51 @@ static void tst4() {
|
|||
}
|
||||
}
|
||||
|
||||
class ex : public exception {
|
||||
std::function<char const *()> m_f;
|
||||
ex(std::function<char const *()> const & f):m_f(f) {}
|
||||
public:
|
||||
template<typename F> ex(F && f):m_f(f) {}
|
||||
virtual exception * clone() const { return new ex(m_f); }
|
||||
virtual void rethrow() const { throw *this; }
|
||||
virtual char const * what() const noexcept { return m_f(); }
|
||||
};
|
||||
|
||||
static void throw_ex() {
|
||||
int x = 10;
|
||||
std::string msg = "foo";
|
||||
throw ex([=]() {
|
||||
static std::string m;
|
||||
std::ostringstream buffer;
|
||||
buffer << "error, x: " << x << " " << msg;
|
||||
m = buffer.str();
|
||||
return m.c_str();
|
||||
});
|
||||
}
|
||||
|
||||
static void throw_catch_rethrow() {
|
||||
try {
|
||||
throw_ex();
|
||||
} catch (ex & e) {
|
||||
std::cout << "CATCH 1: {" << e.what() << "}\n";
|
||||
std::unique_ptr<exception> new_e(e.clone());
|
||||
new_e->rethrow();
|
||||
}
|
||||
}
|
||||
|
||||
static void tst5() {
|
||||
try {
|
||||
throw_catch_rethrow();
|
||||
} catch (ex & e) {
|
||||
std::cout << "CATCH 2: {" << e.what() << "}\n";
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
tst1();
|
||||
tst2();
|
||||
tst3();
|
||||
tst4();
|
||||
tst5();
|
||||
return has_violations() ? 1 : 0;
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue