From ce06c25e93183282be42ab79bfed2ab7c02791ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?louiz=E2=80=99?= Date: Thu, 20 Oct 2016 19:32:20 +0200 Subject: Very little optimization by using a simpler scope_guard when possible MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The version with the vector, that can be disabled etc, is “very” slow, so we use unique_ptr when we don’t need to disable it, and when it only contains one function --- louloulibs/utils/encoding.cpp | 8 ++++---- louloulibs/utils/scopeguard.hpp | 7 +++++++ 2 files changed, 11 insertions(+), 4 deletions(-) (limited to 'louloulibs/utils') diff --git a/louloulibs/utils/encoding.cpp b/louloulibs/utils/encoding.cpp index 507f38a..4b20797 100644 --- a/louloulibs/utils/encoding.cpp +++ b/louloulibs/utils/encoding.cpp @@ -76,7 +76,7 @@ namespace utils { // The given string MUST be a valid utf-8 string unsigned char* res = new unsigned char[original.size()]; - ScopeGuard sg([&res]() { delete[] res;}); + const auto sg = utils::make_scope_guard([&res](auto&&) { delete[] res;}); // pointer where we write valid chars unsigned char* r = res; @@ -140,7 +140,7 @@ namespace utils else throw std::runtime_error("Invalid UTF-8 passed to remove_invalid_xml_chars"); } - return std::string(reinterpret_cast(res), r-res); + return {reinterpret_cast(res), static_cast(r-res)}; } std::string convert_to_utf8(const std::string& str, const char* charset) @@ -152,7 +152,7 @@ namespace utils throw std::runtime_error("Cannot convert into UTF-8"); // Make sure cd is always closed when we leave this function - ScopeGuard sg([&]{ iconv_close(cd); }); + const auto sg = utils::make_scope_guard([&](auto&&){ iconv_close(cd); }); size_t inbytesleft = str.size(); @@ -169,7 +169,7 @@ namespace utils char* outbuf_ptr = outbuf; // Make sure outbuf is always deleted when we leave this function - sg.add_callback([&]{ delete[] outbuf; }); + const auto sg2 = utils::make_scope_guard([&](auto&&){ delete[] outbuf; }); bool done = false; while (done == false) diff --git a/louloulibs/utils/scopeguard.hpp b/louloulibs/utils/scopeguard.hpp index ee1e2ef..cd0e89e 100644 --- a/louloulibs/utils/scopeguard.hpp +++ b/louloulibs/utils/scopeguard.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include /** @@ -85,5 +86,11 @@ private: }; +template +auto make_scope_guard(F&& f) +{ + return std::unique_ptr>{(void*)1, std::forward(f)}; +} + } -- cgit v1.2.3