无法在类

时间:2018-03-26 21:49:00

标签: c++ arrays dynamic delete-operator

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

标题文件:

#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] = '\0';

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();

}

1 个答案:

答案 0 :(得分:4)

circleMarker

这在数组外部写入。 this-&gt; m_capacity为3,所以你要分配3个字符,然后写入第4个字符。

不需要计算机来检测此问题。微软试图通过检测它来帮助它,但只有当你释放内存时它们才会被发现。如果在调试器中运行程序,则应在“调试输出”窗口中看到一些消息,说明程序崩溃的原因。