Created
March 9, 2025 20:54
-
-
Save lll-phill-lll/2234a432b4a113c06229a035e0219136 to your computer and use it in GitHub Desktop.
actually_smart_ptr.h
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
#include <iostream> | |
#include <memory> | |
#include <string> | |
#include <cstdlib> | |
#include <curl/curl.h> | |
const std::string API_KEY = "your_api_key_here"; | |
const std::string LLM_URL = "https://api.openai.com/v1/completions"; | |
template <typename T> | |
class ActuallySmartPointer { | |
private: | |
T* ptr; | |
static size_t WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) { | |
((std::string*)userp)->append((char*)contents, size * nmemb); | |
return size * nmemb; | |
} | |
bool askLLM() { | |
CURL* curl; | |
CURLcode res; | |
std::string readBuffer; | |
curl = curl_easy_init(); | |
if (curl) { | |
std::string prompt = "Based on your knowledge, should I delete the pointer? Answer either yes or no."; | |
std::string postFields = "{\"model\": \"gpt-4\", \"prompt\": \"" + prompt + "\", \"max_tokens\": 5}"; | |
struct curl_slist* headers = nullptr; | |
headers = curl_slist_append(headers, ("Authorization: Bearer " + API_KEY).c_str()); | |
headers = curl_slist_append(headers, "Content-Type: application/json"); | |
curl_easy_setopt(curl, CURLOPT_URL, LLM_URL.c_str()); | |
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); | |
curl_easy_setopt(curl, CURLOPT_POST, 1L); | |
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields.c_str()); | |
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); | |
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); | |
res = curl_easy_perform(curl); | |
curl_easy_cleanup(curl); | |
curl_slist_free_all(headers); | |
if (res == CURLE_OK) { | |
return readBuffer.find("yes") != std::string::npos; | |
} | |
} | |
return false; | |
} | |
public: | |
explicit ActuallySmartPointer(T* p = nullptr) : ptr(p) {} | |
~ActuallySmartPointer() { | |
if (ptr) { | |
if (askLLM()) { | |
delete ptr; | |
} | |
} | |
} | |
T& operator*() const { return *ptr; } | |
T* operator->() const { return ptr; } | |
T* get() const { return ptr; } | |
ActuallySmartPointer(const ActuallySmartPointer&) = delete; | |
ActuallySmartPointer& operator=(const ActuallySmartPointer&) = delete; | |
ActuallySmartPointer(ActuallySmartPointer&& other) noexcept : ptr(other.ptr) { | |
other.ptr = nullptr; | |
} | |
ActuallySmartPointer& operator=(ActuallySmartPointer&& other) noexcept { | |
if (this != &other) { | |
if (ptr && askLLM()) { | |
delete ptr; | |
} | |
ptr = other.ptr; | |
other.ptr = nullptr; | |
} | |
return *this; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment