summaryrefslogtreecommitdiff
path: root/audio/SoundWire/Samples/SdcaVad/Inc/cpp_utils.h
blob: f4ed622073fed0dfc9c9dd460c419fe4b1b801c5 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
/*++

Copyright (c) Microsoft Corporation.  All rights reserved.

    THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
    KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR
    PURPOSE.

Module Name:

    cpp_utils.h

Abstract:

    Contains CPP utilities

Environment:

    Kernel mode

--*/

#pragma once

// Function scope_exit instantiates scope_exit object
// Constructor accepts lamda as parameter.
// Assign tasks in lamdba to be executed on scope exit.
template <typename F>
auto scope_exit(F f)
{
    class scope_exit
    {
    public:
        scope_exit(F f) :
            _f{ f }
        {
        }

        ~scope_exit()
        {
            if (_call)
            {
                _f();
            }
        }

        // Ensures the scope_exit lambda will not be called
        void release()
        {
            _call = false;
        }

        // Executes the scope_exit lambda immediately if not yet run; ensures it will not run again
        void reset()
        {
            if (_call)
            {
                _f();
                _call = false;
            }
        }

    private:
        F _f;
        bool _call = true;
    };

    return scope_exit{ f };
};