From a7ca007e24c32e8408bc8ceb3a745e3a7469f9a2 Mon Sep 17 00:00:00 2001 From: John Maguire Date: Thu, 11 Feb 2016 14:09:36 +0000 Subject: [PATCH] Tidy up lazy implementation. --- ext/libclementine-common/core/lazy.h | 44 +++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/ext/libclementine-common/core/lazy.h b/ext/libclementine-common/core/lazy.h index 43684891c..caf4235fb 100644 --- a/ext/libclementine-common/core/lazy.h +++ b/ext/libclementine-common/core/lazy.h @@ -1,25 +1,55 @@ +/* This file is part of Clementine. + Copyright 2016, John Maguire + + Clementine is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Clementine is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Clementine. If not, see . +*/ + +#ifndef LAZY_H +#define LAZY_H + #include #include +// Helper for lazy initialisation of objects. +// Usage: +// Lazy my_lazy_object([]() { return new Foo; }); template class Lazy { public: explicit Lazy(std::function init) : init_(init) {} - T* get() { - if (!ptr_) { - ptr_.reset(init_()); - } + T* get() const { + CheckInitialised(); return ptr_.get(); } typename std::add_lvalue_reference::type operator*() const { + CheckInitialised(); return *ptr_; } - T* operator->() const { return ptr_.get(); } + T* operator->() const { return get(); } private: - std::function init_; - std::unique_ptr ptr_; + void CheckInitialised() const { + if (!ptr_) { + ptr_.reset(init_()); + } + } + + const std::function init_; + mutable std::unique_ptr ptr_; }; + +#endif // LAZY_H