无法删除在destructor中的成员指针的课程
Unable to delete member pointer to array in destructor for class
因此,我正在尝试删除我的成员指针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试图通过检测到它来帮助您,但是它们的检测仅在您释放内存时才发生。如果您在调试器中运行程序,则应在"调试输出"窗口中查看一些消息,以解释您的程序为何崩溃。
相关文章:
- 从成员指针到整个结构/类的强制转换
- OOP 中的单成员指针
- 使用结构成员指针在C++中填充结构
- 聚合初始化,将成员指针设置为同一结构成员
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 共享 C++ 的数据成员指针
- 如何声明指向成员内容的成员指针m_pmd/m_pmf并访问它们?
- 从类C++外部调用指向成员方法的成员指针
- 结构成员指针是否自动初始化为零?
- 如何删除类内类类型的类成员指针
- 是否打印指向已定义 int 的成员指针
- 指向常量的成员指针
- 通过此指针访问时的成员差异和自身的成员指针(简单的 QT 示例问题)
- 类数据成员指针的非类型模板参数包无法使用 gcc 编译
- 为什么我不能在同一行中定义两个相同类型的类的成员指针
- 将类成员指针传递给 Lambda 捕获列表 c++11
- 在单一实例类中将成员指针设置为 null 的正确方法是什么
- 无法删除在destructor中的成员指针的课程
- 删除对象而不调用成员指针的析构函数
- 当派生类的基类具有成员指针时,对其进行深层复制