har*_*ter 0 c++ destructor reference-counting shared-ptr delete-operator
我是 C++ 的新手,正在尝试对 shared_ptr (WIP) 进行非常基本的实现。我试图在通过取消引用找到基础值后立即在析构函数中删除堆分配的指针。虽然取消引用发生得很好,但删除 '''ref_count''' 变量会导致问题。有人可以帮忙吗?'''
#include<iostream>
template<typename T>
class shared_ptr{
private:
T* native_ptr_ = nullptr;
int* ref_count_ = nullptr;
inline void increment_count() {
*ref_count_++;
}
inline void decrement_count() {
*ref_count_--;
}
public:
shared_ptr() {
std::cout << "shared_ptr: empty constructor" << std::endl;
native_ptr_ = nullptr;
ref_count_ = nullptr;
}
shared_ptr(T* ptr) {
std::cout << "shared_ptr: constructor" << std::endl;
if (ptr) {
native_ptr_ = ptr;
ref_count_ = new int(1);
}
}
~shared_ptr() {
std::cout << "shared_ptr: destructor" << std::endl;
if (ref_count_) {
decrement_count();
if (ref_count_ && use_count() == 0) {
std::cout << *ref_count_ << " " << *native_ptr_ << std::endl;
delete ref_count_;
delete native_ptr_;
ref_count_ = nullptr;
native_ptr_ = nullptr;
}
}
}
int use_count() const {
if(ref_count_) {
return *ref_count_;
} else {
return 0;
}
}
};
int main() {
// case1
int* temp = new int(0);
shared_ptr<int> a1(temp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
'''
'''
shared_ptr: constructor
shared_ptr: destructor
0 0
free(): invalid pointer
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)
'''
运算符优先级会给您带来问题。您实际上是在递减指针,然后推迟新地址。如果你提高你的警告,你会得到这样的东西:
p.cpp:35:7: required from ‘shared_ptr<T>::~shared_ptr() [with T = int]’
p.cpp:58:26: required from here
p.cpp:14:5: warning: value computed is not used [-Wunused-value]
14 | *ref_count_--;
| ^
Run Code Online (Sandbox Code Playgroud)
您可以在递减之前添加括号以取消引用指针。