From bd11b54c75520e78b782eb6b4e25b1ca616466de Mon Sep 17 00:00:00 2001 From: Vladimir Ivanov Date: Sat, 9 Apr 2022 00:49:55 +0300 Subject: [PATCH] Exception example --- examples/vector_size_sample/CMakeLists.txt | 6 ++++++ examples/vector_size_sample/fancy_ptr.cpp | 8 +++++++- examples/vector_size_sample/fancy_ptr.h | 13 ++++++++++++- 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/examples/vector_size_sample/CMakeLists.txt b/examples/vector_size_sample/CMakeLists.txt index 3ce9ebf..73340c2 100644 --- a/examples/vector_size_sample/CMakeLists.txt +++ b/examples/vector_size_sample/CMakeLists.txt @@ -12,3 +12,9 @@ add_executable(fancy_ptr fancy_ptr.h ) +add_executable(fancy_ptr_trace + fancy_ptr.cpp + fancy_ptr.h + stacktrace.cpp + ) + diff --git a/examples/vector_size_sample/fancy_ptr.cpp b/examples/vector_size_sample/fancy_ptr.cpp index 0f519f1..7245e7c 100644 --- a/examples/vector_size_sample/fancy_ptr.cpp +++ b/examples/vector_size_sample/fancy_ptr.cpp @@ -32,9 +32,12 @@ #include "fancy_ptr.h" +#include #include #include +using namespace std; + extern "C" int foo([[maybe_unused]] const int* buf, [[maybe_unused]] unsigned long n) { return 0; } @@ -59,10 +62,13 @@ void foo_at_lvalue(FancyVec& v, size_t n) { v.at(n) = 42; } -void test() { +void test() try { FancyVec v(10); v.insert(v.end(), 42); assert(v.size() == 11); +} catch (std::exception& e) { + cerr << "[ERROR] terminating with exception:\n" << e.what() << endl; +// throw; } // Explicit instantiation diff --git a/examples/vector_size_sample/fancy_ptr.h b/examples/vector_size_sample/fancy_ptr.h index fdaebd1..65ab96e 100644 --- a/examples/vector_size_sample/fancy_ptr.h +++ b/examples/vector_size_sample/fancy_ptr.h @@ -29,8 +29,18 @@ using std::nullptr_t; using std::true_type; +#include +#include +std::string Backtrace(int skip = 1); + namespace my { +class Error : public std::runtime_error { +public: + Error(const std::string& s) : std::runtime_error(s) {} +}; + +inline void throw_my() { throw Error(Backtrace(2)); } template class Ptr; template class CPtr; @@ -114,7 +124,7 @@ struct CPtr { CPtr(nullptr_t) : p_(nullptr) {} CPtr(const T* p) : p_(p) {} - CPtr(const Ptr& p) : CPtr(p.p_) {} + CPtr(const Ptr& p) : p_(p.p_) { throw_my(); } CPtr(const CPtr &) = default; CPtr(CPtr &&) = default; @@ -178,6 +188,7 @@ ptrdiff_t operator-(const Ptr& a, const Ptr b) { return a.p_ - b.p_; } + template class custom_allocator;