Interview problem: Implement shared 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
template<typename T>
class SharedPtr {
public:
    explicit SharedPtr(T *ptr=nullptr): ptr_(ptr), count_(new long(0)) {
        if (ptr_) {
            ++(*count_);
        }
    }

    ~SharedPtr() {
        if (count_) {
            --(*count_);
            if (*count_ == 0) {
                delete count_;
                delete ptr_;
            }
        }
    }

    SharedPtr(const SharedPtr& other): ptr_(other.ptr_), count_(other.count_) {
        ++(*count_);
    }

    SharedPtr& operator=(const SharedPtr& other) {
        SharedPtr tmp(other);
        tmp.swap(*this);
        return *this;
    }
    
    SharedPtr(SharedPtr&& other) noexcept: ptr_(other.ptr_), count_(other.count_) {
        other.ptr_ = nullptr;
        other.count_ = nullptr;
    }
    
    SharedPtr& operator=(SharedPtr&& 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(SharedPtr &other) noexcept {
        std::swap(ptr_, other.ptr_);
        std::swap(count_, other.count_);
    }

private:
    T* ptr_;
    long *count_;
};

Comments

Popular posts from this blog

529 Plan

How to offset W2 tax

Retirement Accounts