File: optional_ptr.h

package info (click to toggle)
bagel 1.2.2-8
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 134,940 kB
  • sloc: cpp: 1,236,571; javascript: 15,383; python: 1,461; ansic: 674; makefile: 253; sh: 109
file content (59 lines) | stat: -rw-r--r-- 1,037 bytes parent folder | download | duplicates (7)
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
#ifndef __BTAS_UTIL_OPTIONAL_PTR_H
#define __BTAS_UTIL_OPTIONAL_PTR_H 1

#include <memory>

namespace btas {

/**

  optional_ptr<T> functions either as a raw unmanaged pointer
  or as a smart pointer of type managed_ptr depending on whether
  it is initialized through the set_external method or
  the set_managed method


*/
template <typename T, typename managed_ptr = std::unique_ptr<T>>
class optional_ptr
    {
    public:

    using ptr = T*;

    optional_ptr() : p_(nullptr) { }

    optional_ptr(optional_ptr&& other)
        :
        p_(other.p_),
        up_(std::move(other.up_))
        { }

    T&
    operator*() const { return *p_; }

    ptr
    operator->() const { return p_; }

    void
    set_managed(ptr new_p)
        {
        up_ = std::move(managed_ptr(new_p));
        p_ = up_.get();
        }

    void
    set_external(ptr ext_p)
        {
        p_ = ext_p;
        up_.reset();
        }

    private:
    ptr p_;
    managed_ptr up_;
    };

} // namespace btas

#endif // __BTAS_UTIL_OPTIONAL_PTR_H