我已经看到了几个shared_ptr的实现,例如这里.所有人都宣称ref_count为int*.我不明白,如果只是一个,我们会失去什么int.谢谢!
template <class T>
class shared_ptr {
T* ptr;
int* ref_count;
/**
* Initializes the ref count used for tracking the usage.
*/
void initialize_ref_count() {
if (ref_count != nullptr)
return;
try {
ref_count = new int;
*ref_count = 1;
}
catch (std::bad_alloc& e) {
std::cerr << "Memory allocation error: " << e.what();
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如您在(在链接中)提供的实现中所看到的,当共享指针被复制构造或复制分配时,指向引用计数器(ref_count)的指针在管理同一指针的所有实例之间共享:
// Copy constructor
shared_ptr(const shared_ptr& copy) {
ptr = copy.ptr;
ref_count = copy.ref_count; // see here
if (ref_count != nullptr) {
++(*ref_count);
}
}
// Assignment operator
shared_ptr& operator=(const shared_ptr& copy) {
ptr = copy.ptr;
ref_count = copy.ref_count; // see here
if (ref_count != nullptr) {
++(*ref_count);
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
这样,该共享指针的所有实例都引用相同的内存位置来跟踪ref计数器,最后一个shared_ptr将能够知道它是否需要进行清理(delete分配的内存):
~shared_ptr() {
--(*ref_count);
if (*ref_count == 0) {
delete ref_count;
ref_count = nullptr;
delete ptr;
ptr = nullptr;
}
}
Run Code Online (Sandbox Code Playgroud)
这个答案基于OP为简单起见提供的示例.一个shared_ptr实现更为复杂的是,一个在本例中(想想原子,比赛条件等).
| 归档时间: |
|
| 查看次数: |
851 次 |
| 最近记录: |