小编har*_*ter的帖子

为什么删除有效的堆分配指针会导致“free(): invalid pointer”错误?

我是 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; …
Run Code Online (Sandbox Code Playgroud)

c++ destructor reference-counting shared-ptr delete-operator

0
推荐指数
1
解决办法
224
查看次数