Skip to content

Commit

Permalink
Update ScopeGuard example
Browse files Browse the repository at this point in the history
  • Loading branch information
uchenily committed Jun 10, 2024
1 parent 5202dde commit e6e2481
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
54 changes: 53 additions & 1 deletion tests/test_scopeexit.cpp
Original file line number Diff line number Diff line change
@@ -1,13 +1,65 @@
#include "uvio/common/scope_exit.hpp"
#include "uvio/debug.hpp"
#include <sstream>

using namespace uvio;

auto main() -> int {
void basic() {
LOG_INFO("allocate resource");
AddScopeExitGuard([]() {
LOG_INFO("recovery resource");
});

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();
}
4 changes: 2 additions & 2 deletions uvio/common/scope_exit.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace uvio {

template <typename Func>
struct ScopeGuard final {
ScopeGuard(Func func)
: func_{std::move(func)} {}
ScopeGuard(Func &&func)
: func_{std::forward<Func>(func)} {}

~ScopeGuard() {
if (active_) {
Expand Down

0 comments on commit e6e2481

Please sign in to comment.