aboutsummaryrefslogtreecommitdiffstats
path: root/vespalib/src/vespa/vespalib/util/varholder.h
blob: db8109fca708e9854bfbf12e0b5a3169d63cb373 (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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#pragma once

#include <mutex>

namespace vespalib {

template <typename T>
class VarHolder
{
    T                   _v;
    mutable std::mutex  _lock;
public:
    VarHolder() : _v(), _lock() {}
    explicit VarHolder(T v) : _v(std::move(v)), _lock() {}
    VarHolder(const VarHolder &) = delete;
    VarHolder & operator = (const VarHolder &) = delete;
    ~VarHolder();

    void set(T v) {
        T old;
        {
            std::lock_guard guard(_lock);
            old = std::move(_v);
            _v = std::move(v);
        }
    }

    void clear() { set(T()); }

    T get() const {
        std::lock_guard guard(_lock);
        return _v;
    }
};

template <typename T>
VarHolder<T>::~VarHolder() = default;

}