2019-02-22 20:24:38 +01:00
|
|
|
/* This file is part of Strawberry.
|
2018-02-27 18:06:05 +01:00
|
|
|
Copyright 2016, John Maguire <john.maguire@gmail.com>
|
|
|
|
|
2019-02-22 20:24:38 +01:00
|
|
|
Strawberry is free software: you can redistribute it and/or modify
|
2018-02-27 18:06:05 +01:00
|
|
|
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.
|
|
|
|
|
2019-02-22 20:24:38 +01:00
|
|
|
Strawberry is distributed in the hope that it will be useful,
|
2018-02-27 18:06:05 +01:00
|
|
|
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
|
2019-02-22 20:24:38 +01:00
|
|
|
along with Strawberry. If not, see <http://www.gnu.org/licenses/>.
|
2018-02-27 18:06:05 +01:00
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef LAZY_H
|
|
|
|
#define LAZY_H
|
|
|
|
|
|
|
|
#include <functional>
|
|
|
|
#include <memory>
|
|
|
|
|
2020-09-04 20:25:46 +02:00
|
|
|
// Helper for lazy initialization of objects.
|
2018-02-27 18:06:05 +01:00
|
|
|
// Usage:
|
|
|
|
// Lazy<Foo> my_lazy_object([]() { return new Foo; });
|
|
|
|
|
2022-03-22 21:09:05 +01:00
|
|
|
template<typename T>
|
2018-02-27 18:06:05 +01:00
|
|
|
class Lazy {
|
|
|
|
public:
|
|
|
|
explicit Lazy(std::function<T*()> init) : init_(init) {}
|
|
|
|
|
|
|
|
// Convenience constructor that will lazily default construct the object.
|
|
|
|
Lazy() : init_([]() { return new T; }) {}
|
|
|
|
|
|
|
|
T* get() const {
|
2020-10-17 17:29:09 +02:00
|
|
|
CheckInitialized();
|
2018-02-27 18:06:05 +01:00
|
|
|
return ptr_.get();
|
|
|
|
}
|
|
|
|
|
|
|
|
typename std::add_lvalue_reference<T>::type operator*() const {
|
2020-10-17 17:29:09 +02:00
|
|
|
CheckInitialized();
|
2018-02-27 18:06:05 +01:00
|
|
|
return *ptr_;
|
|
|
|
}
|
|
|
|
|
|
|
|
T* operator->() const { return get(); }
|
|
|
|
|
2020-10-17 17:29:09 +02:00
|
|
|
// Returns true if the object is not yet initialized.
|
2018-02-27 18:06:05 +01:00
|
|
|
explicit operator bool() const { return ptr_; }
|
|
|
|
|
2020-10-17 17:29:09 +02:00
|
|
|
// Deletes the underlying object and will re-run the initialization function if the object is requested again.
|
2020-09-04 20:25:46 +02:00
|
|
|
void reset() { ptr_.reset(); }
|
2018-02-27 18:06:05 +01:00
|
|
|
|
|
|
|
private:
|
2020-10-17 17:29:09 +02:00
|
|
|
void CheckInitialized() const {
|
2018-02-27 18:06:05 +01:00
|
|
|
if (!ptr_) {
|
2020-09-04 20:25:46 +02:00
|
|
|
ptr_.reset(init_(), [](T*obj) { obj->deleteLater(); });
|
2018-02-27 18:06:05 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const std::function<T*()> init_;
|
2020-09-04 20:25:46 +02:00
|
|
|
mutable std::shared_ptr<T> ptr_;
|
2018-02-27 18:06:05 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
#endif // LAZY_H
|