From b9df8cdb021de938a25e47e9c2d2a81c1d064c83 Mon Sep 17 00:00:00 2001 From: Bob Polis Date: Wed, 2 Sep 2020 10:59:31 +0200 Subject: [PATCH] refactored into a proper RAII class for a curl handle --- requester.cpp | 22 ++++++++++++++++++++++ requester.hpp | 15 ++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/requester.cpp b/requester.cpp index 64dedf9..60858e9 100644 --- a/requester.cpp +++ b/requester.cpp @@ -30,6 +30,28 @@ requester::requester() { curl_easy_setopt(_h, CURLOPT_WRITEFUNCTION, write_data); } +requester::~requester() { + if (_h) { + curl_easy_cleanup(_h); + } +} + +requester::requester(requester&& other) { + _h = other._h; + other._h = nullptr; +} + +requester& requester::operator=(requester &&other) { + if (this != &other) { + if (_h) { + curl_easy_cleanup(_h); + } + _h = other._h; + other._h = nullptr; + } + return *this; +} + std::string requester::get(const std::string &url) { curl_easy_setopt(_h, CURLOPT_URL, url.c_str()); std::vector buf; diff --git a/requester.hpp b/requester.hpp index fbf6deb..a58d479 100644 --- a/requester.hpp +++ b/requester.hpp @@ -14,14 +14,27 @@ class requester { public: + // callback for data receiving static size_t write_data(char* buf, size_t sz, size_t nmemb, void* user_data); + // this class is a RAII class for a curl handle requester(); + + // forbid copying + requester(const requester& other) = delete; + requester& operator=(const requester& other) = delete; + + // allow moving + requester(requester&& other); + requester& operator=(requester&& other); + + // cleanup + ~requester(); std::string get(const std::string& url); private: - CURL* _h; + CURL* _h; // curl handle }; #endif // _requester_H_