Interview problem: Implement unique pointer

 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
template <typename T>
class UniquePtr {
public:
    explicit UniquePtr(T *ptr=nullptr): ptr_(ptr){}

    ~UniquePtr(){
        delete ptr_;
    }

    UniquePtr(const UniquePtr &other) = delete;

    UniquePtr& operator=(const UniquePtr &other) = delete;

    UniquePtr(UniquePtr &&other) noexcept: ptr_(other.ptr_) {
        other.ptr_ = nullptr;
    }

    UniquePtr& operator=(UniquePtr &&other) noexcept {
        other.swap(*this);
        return *this;
    }

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

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

    explicit operator bool() const {
        return ptr_;
    }

    void swap(UniquePtr &other) noexcept {
        std::swap(ptr_, other.ptr_);
    }

private:
    T *ptr_;
};

Comments

Popular posts from this blog

529 Plan

How to offset W2 tax

Health Saving Account (HSA)