Skip to content

Instantly share code, notes, and snippets.

@voidbar
Last active August 25, 2022 20:58
Show Gist options
  • Save voidbar/ad656d01deef78368606fdd2012e48b0 to your computer and use it in GitHub Desktop.
Save voidbar/ad656d01deef78368606fdd2012e48b0 to your computer and use it in GitHub Desktop.
Simple Meyers singleton example C++17
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include <format> // Requires C++20
using system_clock = std::chrono::system_clock;
using namespace std::chrono_literals;
const std::string& get_static_message() {
// Will be constructed exactly once
static const std::string msg = std::to_string(system_clock::now().time_since_epoch().count());
return msg;
}
int main() {
std::cout << std::format("First invocation: {}\n", get_static_message());
std::this_thread::sleep_for(5s);
std::cout << std::format("Second invocation: {}\n", get_static_message());
// Possible output, note that the result from the get_static_message is the same!:
// First invocation: 16614610160060892
// Second invocation: 16614610160060892
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment