Skip to content

Introduce RAII-Scope Guard instead of using std::shared_ptr #1180

Description

@Curve

The http client currently uses an empty std::shared_ptr<int> as a scope-guard to run cleanup code:

std::shared_ptr<int> guard(nullptr, [this](auto) {
if (!req_headers_.empty()) {
req_headers_.clear();
}
});

If I'm not mistaken, this will still have to allocate a shared state to store the user defined destructor in, which is quite wasteful. I'd suggest to introduce a simple scope guard for this purpose instead of abusing std::shared_ptr for this:

template <typename T>
struct scope_guard
{
  T callback;

public:
  explicit scope_guard(T callback) : callback(std::move(callback)) {} 

public: 
  scope_guard(const scope_guard&) = delete;
  scope_guard(scope_guard&&) noexcept = delete;

public:
  ~scope_guard() { callback(); }
};

You could also leave out the deleted ctors and make it an aggregate for cleaner construction :)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions