【发布时间】:2018-03-26 21:49:00
【问题描述】:
所以我试图删除我的成员指针m_memory,因为它指向char 的数组。当我尝试使用delete[] 删除 m_memory 指向的数组时,我最终触发了断点。在使用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] = '\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();
}
【问题讨论】:
-
我还想提一下,我尝试删除指针而不添加 this-> 无济于事。
-
隐约相关:你很少想自己调用析构函数,所以
nemo->~Fish();应该是delete nemo; -
我们是否可以假设存在阻止使用
std::string的限制? -
没有。您不必调用析构函数。使析构函数
virtual并通过多态的魔力,无论是在基类还是子类上操作,都会调用正确的析构函数。 -
显示复制构造函数的代码。这很可能就是问题所在。
标签: c++ arrays dynamic delete-operator