aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/misc/non_null_ptr.h
blob: 0005e4edb666a88c98c0da03ab824de68d7deaa6 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#pragma once

#include "concepts.h"

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

// We have one really strange rule in our codestyle - mutable arguments are passed by pointer.
// But if you are not a fan of making your life indefinite,
// you can use this helper, that will validate that pointer you pass is not null.
template <class T>
class TNonNullPtr;

template <class T>
class TNonNullPtrBase
{
public:
    TNonNullPtrBase(T* ptr) noexcept;
    TNonNullPtrBase(const TNonNullPtrBase& other) = default;

    TNonNullPtrBase(std::nullptr_t) = delete;
    TNonNullPtrBase operator=(const TNonNullPtrBase&) = delete;

    T* operator->() const noexcept;
    T& operator*() const noexcept;

protected:
    T* Ptr_;

    TNonNullPtrBase() noexcept;
};

template <class T>
TNonNullPtr<T> GetPtr(T& ref) noexcept;

template <class T>
class TNonNullPtr
    : public TNonNullPtrBase<T>
{
    using TConstPtr = TNonNullPtr<const T>;
    friend TConstPtr;

    using TNonNullPtrBase<T>::TNonNullPtrBase;

    friend TNonNullPtr<T> GetPtr<T>(T& ref) noexcept;
};

// NB(pogorelov): Method definitions placed in .h file (instead of -inl.h) because of clang16 bug.
// TODO(pogorelov): Move method definitions to helpers-inl.h when new clang will be used.
template <CConst T>
class TNonNullPtr<T>
    : public TNonNullPtrBase<T>
{
    using TMutPtr = TNonNullPtr<std::remove_const_t<T>>;

    using TNonNullPtrBase<T>::TNonNullPtrBase;

    friend TNonNullPtr<T> GetPtr<T>(T& ref) noexcept;

public:
    TNonNullPtr(TMutPtr mutPtr) noexcept
        : TNonNullPtrBase<T>()
    {
        TNonNullPtrBase<T>::Ptr_ = mutPtr.Ptr_;
    }
};


////////////////////////////////////////////////////////////////////////////////

} // namespace NYT

#define NON_NULL_PTR_H_
#include "non_null_ptr-inl.h"
#undef NON_NULL_PTR_H_