aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/destructor_callbacks.h
blob: 317c921811cb3d15a9a5f405244e042ae36df12f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include "idestructorcallback.h"

namespace vespalib {

class Gate;

class GateCallback : public IDestructorCallback {
public:
    explicit GateCallback(vespalib::Gate & gate) noexcept : _gate(gate) {}
    ~GateCallback() override;
private:
    vespalib::Gate & _gate;
};

class IgnoreCallback : public IDestructorCallback {
public:
    IgnoreCallback() noexcept { }
    ~IgnoreCallback() override = default;
};

template <typename T>
struct KeepAlive : public IDestructorCallback {
    explicit KeepAlive(T toKeep) noexcept : _toKeep(std::move(toKeep)) { }
    ~KeepAlive() override = default;
    T _toKeep;
};

template<class FunctionType>
class LambdaCallback : public IDestructorCallback {
public:
    explicit LambdaCallback(FunctionType &&func) noexcept
        : _func(std::move(func))
    {}
    ~LambdaCallback() {
        _func();
    }
private:
    FunctionType _func;
};

template<class FunctionType>
std::shared_ptr<IDestructorCallback>
makeSharedLambdaCallback(FunctionType &&function) {
    return std::make_shared<LambdaCallback<std::decay_t<FunctionType>>>
            (std::forward<FunctionType>(function));
}

template<class FunctionType>
std::unique_ptr<IDestructorCallback>
makeUniqueLambdaCallback(FunctionType &&function) {
    return std::make_unique<LambdaCallback<std::decay_t<FunctionType>>>
            (std::forward<FunctionType>(function));
}


}