Skip to content

Instantly share code, notes, and snippets.

@gchudnov
Created November 6, 2014 19:39
Show Gist options
  • Save gchudnov/155ec120ac0cf9366ce1 to your computer and use it in GitHub Desktop.
Save gchudnov/155ec120ac0cf9366ce1 to your computer and use it in GitHub Desktop.
Lazy (call once)
#include <iostream>
#include <memory>
#include <functional>
#include <mutex>
template <typename T>
struct lazy {
public:
template <typename Fun>
explicit lazy(Fun&& fun) : fun(std::forward<Fun>(fun)) {}
T& get() const {
std::call_once(flag, [this] { ptr.reset(fun()); });
return *ptr;
}
private:
std::once_flag flag;
std::unique_ptr<T> ptr;
std::function<T*()> fun;
};
class foo {};
int main() {
lazy<foo> x([] { return new foo; });
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment