summaryrefslogtreecommitdiffstats
path: root/yql/essentials/utils/checked_deref_ptr.h
blob: 6241574f3c6ad935cf41314af6d1e9a7e86fcef6 (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
77
78
79
80
81
82
83
84
#pragma once

#include "yql_panic.h"

#include <util/generic/utility.h>

namespace NYql {

/**
 * @brief Template wrapper for raw pointers with null-safety checks.
 *
 * Provides automatic null-checking on dereference operations (-> and *).
 * Implicitly converts to raw pointer for seamless integration with existing code.
 */
template <typename T>
class TCheckedDerefPtr {
public:
    constexpr TCheckedDerefPtr() noexcept
        : Ptr_(nullptr)
    {
    }

    explicit constexpr TCheckedDerefPtr(T* ptr) noexcept
        : Ptr_(ptr)
    {
    }

    constexpr TCheckedDerefPtr(const TCheckedDerefPtr& other) noexcept = default;
    constexpr TCheckedDerefPtr(TCheckedDerefPtr&& other) noexcept = default;

    TCheckedDerefPtr& operator=(const TCheckedDerefPtr& other) noexcept = default;
    TCheckedDerefPtr& operator=(TCheckedDerefPtr&& other) noexcept = default;

    TCheckedDerefPtr& operator=(T* ptr) noexcept {
        Ptr_ = ptr;
        return *this;
    }

    T& operator*() const {
        YQL_ENSURE(Ptr_ != nullptr, "Attempt to dereference null pointer");
        return *Ptr_;
    }

    T* operator->() const {
        YQL_ENSURE(Ptr_ != nullptr, "Attempt to access member through null pointer");
        return Ptr_;
    }

    // NOLINTNEXTLINE(google-explicit-constructor)
    constexpr operator T*() const noexcept {
        return Ptr_;
    }

    constexpr explicit operator bool() const noexcept {
        return Ptr_ != nullptr;
    }

    [[nodiscard]] constexpr T* Get() const noexcept {
        return Ptr_;
    }

    void Reset() noexcept {
        Ptr_ = nullptr;
    }

    void Reset(T* ptr) noexcept {
        Ptr_ = ptr;
    }

    void Swap(TCheckedDerefPtr& other) noexcept {
        DoSwap(Ptr_, other.Ptr_);
    }

private:
    T* Ptr_;
};

template <typename T>
// NOLINTNEXTLINE(readability-identifier-naming)
void swap(TCheckedDerefPtr<T>& lhs, TCheckedDerefPtr<T>& rhs) noexcept {
    lhs.Swap(rhs);
}

} // namespace NYql