c++ - 为什么删除有效的堆分配指针会产生“free():无效指针”错误?
问题描述
我是 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;
}
'''
'''
shared_ptr: constructor
shared_ptr: destructor
0 0
free(): invalid pointer
Aborted (core dumped)
'''
解决方案
运算符优先级导致您出现问题。您实际上是在递减指针,然后推迟新地址。如果你提高警告,你会得到这样的东西:
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_--;
| ^
您可以在递减之前添加括号以取消引用指针。
推荐阅读
- sql - 元数据库 - 建立与数据库的连接时运行初始化 SQL
- hyperledger-fabric - 私人通道状态或区块是否添加到主分类账中?
- python - 如何将用户限制为最多三个错误的 otp 条目
- python - 将列表列表(用逗号分隔的语句)展平为列表列表
- python - ValueError: 请在写入数据时传递 `features` 或至少一个示例
- python - 使用 Flask 从镜像凸轮网站保存图像
- docker - Jenkins 构建 docker 镜像失败,代码非零:137
- sql - 如何正确更新多对一实体 - 如何使用 OrderItem 更新 Order
- typescript - 如何在 SublimeText 中禁用下划线变量?
- android - “nativeSdkIntegration 无法安装”android 上的 sentry_flutter 错误