mirror of
https://github.com/clementine-player/Clementine
synced 2025-01-23 16:01:43 +01:00
Add an optional delete function for Lazy pointers.
This allows a delete function to be provided with the prototype: void d(T*) This function is passed to the unique_ptr constructor to be used when the object is released. The default function simply deletes the object, where the default behavior for unique_ptr would have a specialization for arrays. If Lazy is ever used with arrays, a delete function should be provided.
This commit is contained in:
parent
912589439e
commit
5b918a70aa
@ -22,15 +22,25 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
// Helper for lazy initialisation of objects.
|
// Helper for lazy initialisation of objects.
|
||||||
// Usage:
|
// Usage1:
|
||||||
// Lazy<Foo> my_lazy_object([]() { return new Foo; });
|
// Lazy<Foo> my_lazy_object([]() { return new Foo; });
|
||||||
|
// Usage2:
|
||||||
|
// Lazy<Foo> my_lazy_object([]() { return new Foo; },
|
||||||
|
// [](Foo *foo) { delete foo; });
|
||||||
|
// Note: the Lazy::default_deleter just deletes the object. The default
|
||||||
|
// unique_ptr would have a specialization for arrays. The second usage
|
||||||
|
// should be used with arrays.
|
||||||
|
//
|
||||||
template <typename T>
|
template <typename T>
|
||||||
class Lazy {
|
class Lazy {
|
||||||
public:
|
public:
|
||||||
explicit Lazy(std::function<T*()> init) : init_(init) {}
|
explicit Lazy(std::function<T*()> init,
|
||||||
|
std::function<void(T*)> deleter = Lazy::default_deleter)
|
||||||
|
: init_(init), ptr_(nullptr, deleter) {}
|
||||||
|
|
||||||
// Convenience constructor that will lazily default construct the object.
|
// Convenience constructor that will lazily default construct the object.
|
||||||
Lazy() : init_([]() { return new T; }) {}
|
Lazy()
|
||||||
|
: init_([]() { return new T; }), ptr_(nullptr, Lazy::default_deleter) {}
|
||||||
|
|
||||||
T* get() const {
|
T* get() const {
|
||||||
CheckInitialised();
|
CheckInitialised();
|
||||||
@ -51,6 +61,8 @@ class Lazy {
|
|||||||
// if the object is requested again.
|
// if the object is requested again.
|
||||||
void reset() { ptr_.reset(nullptr); }
|
void reset() { ptr_.reset(nullptr); }
|
||||||
|
|
||||||
|
static void default_deleter(T* obj) { delete obj; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void CheckInitialised() const {
|
void CheckInitialised() const {
|
||||||
if (!ptr_) {
|
if (!ptr_) {
|
||||||
@ -59,7 +71,7 @@ class Lazy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const std::function<T*()> init_;
|
const std::function<T*()> init_;
|
||||||
mutable std::unique_ptr<T> ptr_;
|
mutable std::unique_ptr<T, std::function<void(T*)>> ptr_;
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // LAZY_H
|
#endif // LAZY_H
|
||||||
|
Loading…
Reference in New Issue
Block a user