无法删除在destructor中的成员指针的课程

Unable to delete member pointer to array in destructor for class

本文关键字:成员 指针 删除 destructor      更新时间:2023-10-16

因此,我正在尝试删除我的成员指针m_memory,因为它指向char的数组。当我尝试删除m_memory指向使用delete[]的数组时,我最终会触发断点。在使用new之前,我尝试将m_memory初始化为nullptr,但仍然触发了断点。只是想知道我的错误是什么。

标题文件:

#ifndef FISH_H
#define FISH_H
#include <iostream>
class Fish {
public:
    Fish(int capacity, std::string name);// Constructor
    Fish(const Fish &other); // Copy Constructor
    ~Fish(); // Destructor
    Fish &operator=(const Fish &other); // Assignment Operator
    void remember(char c); // Remember c
    void forget(); // Clears memory by filling in '.'
    void printMemory() const;// Prints memory
    std::string getName();
protected:
    const char* getMemory() const;// Returns memory
    int getAmount() const; // Returns amount remembered
    int getCapacity() const; // Returns memory capacity
private:
    std::string m_name;
    char * m_memory;
    int m_capacity;
    int m_remembered;
int m_replace;
};
#endif

实现文件:

#include “fish.”
Fish::Fish(int capacity, std::string name) {// Constructor
    this->m_capacity = capacity;
    if (capacity > 0) {
        this->m_capacity = capacity;
    }
    else {
        this->m_capacity = 3;
    }
this->m_name = name;
this->m_memory = new char[this->m_capacity];
this->m_memory[this->m_capacity] = '';
for (int i = 0; i < this->m_capacity; i++) {
    this->m_memory[i] = '.';
    }
    this->m_remembered = 0;
    this->m_replace = 0;
}

Fish::~Fish() // Destructor
    {
        delete [] this->m_memory; //exception thrown, breakpoint triggered
    }

主:

#include "fish.h"
int main() {
    Fish *nemo = new Fish(3, "nemo");
    nemo->~Fish();
}
this->m_memory = new char[this->m_capacity];
this->m_memory[this->m_capacity] = '';

这在阵列外写入。这 -> m_capacity是3,所以您要分配3个字符,然后写入第四个字符。

不需要计算机检测此问题。Microsoft试图通过检测到它来帮助您,但是它们的检测仅在您释放内存时才发生。如果您在调试器中运行程序,则应在"调试输出"窗口中查看一些消息,以解释您的程序为何崩溃。