Last active
December 14, 2021 16:58
-
-
Save elmazzun/ae284d1503df56676fb575c8e45c2019 to your computer and use it in GitHub Desktop.
Singleton example (C++11)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Curl.hpp | |
#ifndef CURL_HPP | |
#define CURL_HPP | |
#include <iostream> | |
#include <curl/curl.h> | |
// This Singleton is NOT thread-safe (perdoname madre por mi vida loca) | |
class Curl { | |
private: | |
static Curl * _instance; | |
protected: | |
Curl(); | |
~Curl(); | |
public: | |
// This is a Singleton: disable all kinds of copy/move | |
Curl(const Curl&) = delete; | |
Curl(Curl&&) = delete; | |
Curl& operator=(const Curl&) = delete; | |
Curl& operator=(Curl&&) = delete; | |
static Curl *GetInstance(); | |
std::string get(const std::string& url); | |
}; | |
#endif // CURL_HPP | |
// Curl.cpp | |
#include "Curl.hpp" | |
Curl* Curl::_instance = nullptr; | |
// "curl_global_init is not thread safe. You must not call it when any other | |
// thread in the program (i.e. a thread sharing the same memory) is running." | |
// (https://curl.se/libcurl/c/curl_global_init.html) | |
Curl::Curl() { | |
CURLcode ret = curl_global_init(CURL_GLOBAL_DEFAULT); | |
if (ret != CURLE_OK) { | |
std::cout << "Curl init BAD:" << curl_easy_strerror(ret) << std::endl; | |
} else { | |
std::cout << "Curl init OK" << std::endl; | |
} | |
} | |
Curl::~Curl() { | |
curl_global_cleanup(); | |
} | |
Curl * Curl::GetInstance() { | |
if (_instance == nullptr) { | |
_instance = new Curl(); | |
} | |
return _instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment