问题

  1. 实现一个 shared_ptr,需要注意哪些关键点?(引用计数、拷贝构造、赋值操作符、thread safe等)
  2. 无序数组中找到出现次数超过 n/2 的元素,要求常数空间复杂度

参考回答

  1. 实现一个 shared_ptr,需要注意哪些关键点?(引用计数、拷贝构造、赋值操作符、thread safe等)
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
template<typename T>
class SharedPtr {
private:
T* ptr_;
int* count_;
std::mutex* mutex_;

void release() {
bool should_delete = false;
{
std::lock_guard<std::mutex> lock(*mutex_);
if (--(*count_) == 0) {
should_delete = true;
}
}
if (should_delete) {
delete ptr_;
delete count_;
delete mutex_;
}
}

public:
// 构造函数
explicit SharedPtr(T* ptr = nullptr)
: ptr_(ptr), count_(new int(1)), mutex_(new std::mutex) {}

// 拷贝构造函数
SharedPtr(const SharedPtr& other)
: ptr_(other.ptr_), count_(other.count_), mutex_(other.mutex_) {
std::lock_guard<std::mutex> lock(*mutex_);
++(*count_);
}

// 赋值操作符
SharedPtr& operator=(const SharedPtr& other) {
if (this != &other) {
release(); // 释放当前资源

ptr_ = other.ptr_;
count_ = other.count_;
mutex_ = other.mutex_;

std::lock_guard<std::mutex> lock(*mutex_);
++(*count_);
}
return *this;
}

// 移动语义
SharedPtr(SharedPtr&& other) noexcept
: ptr_(other.ptr_), count_(other.count_), mutex_(other.mutex_) {
other.ptr_ = nullptr;
other.count_ = nullptr;
other.mutex_ = nullptr;
}

~SharedPtr() { release(); }

T& operator*() { return *ptr_; }
T* operator->() { return ptr_; }
T* get() { return ptr_; }
int use_count() { return count_ ? *count_ : 0; }
};
cpp

本站由 Zane Jiang 使用 Stellar 1.33.1 主题创建,一款很棒的 Hexo 主题!

总访问 次 || 本页访问
总访客 人 || 本页访客