From e6e248177d80e9d6fefc414370b60ba01743b62d Mon Sep 17 00:00:00 2001 From: uchenily Date: Mon, 10 Jun 2024 18:51:21 +0800 Subject: [PATCH] Update ScopeGuard example --- tests/test_scopeexit.cpp | 54 +++++++++++++++++++++++++++++++++++++- uvio/common/scope_exit.hpp | 4 +-- 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/tests/test_scopeexit.cpp b/tests/test_scopeexit.cpp index 83a60f6..0643801 100644 --- a/tests/test_scopeexit.cpp +++ b/tests/test_scopeexit.cpp @@ -1,9 +1,10 @@ #include "uvio/common/scope_exit.hpp" #include "uvio/debug.hpp" +#include using namespace uvio; -auto main() -> int { +void basic() { LOG_INFO("allocate resource"); AddScopeExitGuard([]() { LOG_INFO("recovery resource"); @@ -11,3 +12,54 @@ auto main() -> int { LOG_INFO("program running ..."); } + +struct HtmlTag { + void add_tag(std::string_view tag_name) { + out_ << std::format("<{}>", tag_name); + } + void close_tag(std::string_view tag_name) { + out_ << std::format("", tag_name); + } + + void add(std::string_view content) { + out_ << content; + } + + void print_html() const { + std::cout << out_.view(); + } + + std::stringstream out_; +}; + +void member_func() { + HtmlTag html_tag; + { + html_tag.add_tag("html"); + AddScopeExitGuard([&]() { + html_tag.close_tag("html"); + }); + { + html_tag.add_tag("h1"); + AddScopeExitGuard([&]() { + html_tag.close_tag("h1"); + }); + html_tag.add("This is title"); + } + { + html_tag.add_tag("p"); + AddScopeExitGuard([&]() { + html_tag.close_tag("p"); + }); + html_tag.add( + "Lorem ipsum dolor sit amet, qui minim labore adipisicing " + "minim sint cillum sint consectetur cupidatat."); + } + } + html_tag.print_html(); +} + +auto main() -> int { + basic(); + member_func(); +} diff --git a/uvio/common/scope_exit.hpp b/uvio/common/scope_exit.hpp index ce8e7cf..7b2fdcc 100644 --- a/uvio/common/scope_exit.hpp +++ b/uvio/common/scope_exit.hpp @@ -5,8 +5,8 @@ namespace uvio { template struct ScopeGuard final { - ScopeGuard(Func func) - : func_{std::move(func)} {} + ScopeGuard(Func &&func) + : func_{std::forward(func)} {} ~ScopeGuard() { if (active_) {