summaryrefslogtreecommitdiff
path: root/include/toBeSorted/raii_ptr.h
blob: 22bab4d49aeb165352fa44ada0f5d219eec6aac4 (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
#ifndef RAII_PTR_H
#define RAII_PTR_H

#include "common.h"

// This could be std::unique_ptr, but we don't have it yet
template <typename T>
class RaiiPtr {
public:
    T *mPtr;

    RaiiPtr() : mPtr(nullptr) {}
    ~RaiiPtr() {
        if (mPtr != nullptr) {
            delete mPtr;
            mPtr = nullptr;
        }
    }

    void destruct() {
        if (mPtr != nullptr) {
            delete mPtr;
            mPtr = nullptr;
        }
    }

    void operator=(T *ptr) {
        mPtr = ptr;
    }

    operator bool() const {
        return mPtr != nullptr;
    }

    const T *get() const {
        return mPtr;
    }

    T *get() {
        return mPtr;
    }

    const T *operator->() const {
        return mPtr;
    }

    T *operator->() {
        return mPtr;
    }

    const T &operator*() const {
        return *this->operator->();
    }

    T &operator*() {
        return *this->operator->();
    }
};

#endif