Last active
August 25, 2022 20:58
-
-
Save voidbar/ad656d01deef78368606fdd2012e48b0 to your computer and use it in GitHub Desktop.
Simple Meyers singleton example C++17
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 <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