[英]Deallocate a pointer array - C++
所以..我一直在努力解除分配数组。
我不知道为什么会发生记忆泄漏,但不知何故。
除了主功能之外,我没有分配任何内存。
#include <iostream>
#include "Motorboat.h"
#include "Sailboat.h"
using namespace std;
void printSailBoats(Boat* arr[], int nrOfElements);
int main() {
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // used to check for memoryleaks in debug mode
Boat* test[4];
int nrOfElements = 4;
test[0] = new Motorboat("heeelllooo",15000,"v100");
test[1] = new Sailboat("saaailboat",1004,43.5);
test[2] = new Motorboat("ASDK",4932,"Blabla");
test[3] = new Sailboat("DKEOK",4992,103.4);
printSailBoats(test,nrOfElements);
for(int i=0; i<4; i++) {
delete test[i];
}
return 0;
}
void printSailBoats(Boat* arr[], int nrOfElements) {
// prints all sailboats
}
编辑:添加了类。 Boat.h:
#ifndef BOAT_H
#define BOAT_H
#include <string>
using namespace std;
class Boat {
public:
virtual void setModel(string newModel) = 0;
virtual void setPrice(int newPrice) = 0;
virtual string getModel() const = 0;
virtual int getPrice() const = 0;
virtual string getType() const = 0;
virtual string toString() const = 0;
};
#endif
Sailboat.h:
#ifndef SAILBOAT_H
#define SAILBOAT_H
#include "Boat.h"
class Sailboat: public Boat {
private:
double sailArea;
string model;
int price;
public:
Sailboat(string model, int price, double sailArea);
void setSailArea(double newSailArea);
double getSailArea() const;
string toString() const;
void setModel(string newModel);
void setPrice(int newPrice);
string getModel() const;
int getPrice() const;
string getType() const;
};
#endif
Sailboat.cpp:
#include "Sailboat.h"
Sailboat::Sailboat(string model, int price, double sailArea) {
this->model = model;
this->price = price;
this->sailArea = sailArea;
}
// Setters, getters and toString...
除了没有用于存储引擎名称而不是sailarea的字符串变量之外,对于摩托艇类几乎是相同的。
泄漏在这里:
for(int i=0; i<4; i++) {
delete test[i];
}
它正在删除元素,就好像它们与基类的类型一样。 IE,如果您的派生类中有任何“额外”信息,它将被泄漏。
例如:
delete (Sailboat*)test[i]
与...不同
delete (Boat*)test[i]
您需要先将test [i]转换为适当的类型,然后再将其删除。 回收实例化的类型可能很困难,因此我建议您只使用智能指针,而不用担心删除。
编辑:此外,虚拟析构函数将解决此问题。 我仍然全力以赴;)
这可能是构造函数中的漏洞。 我的建议是为定义的每个类创建析构函数,以确保删除在构造函数中创建的所有对象。
您可以做的就是添加
#define _CRTDBG_MAP_ALLOC
#include <Crtdbg.h>
随着内存泄漏输出,它应该为您分配剩余块分配到的文件和行。
另外,放置一个printf("Destructor of xxxx\\n");
等等。在每个破坏者(船,帆船,摩托艇)中。 这些应在删除时调用/打印。
但是只有在基本调用(Baot)的析构函数标记为虚拟时,它们才会被调用。 否则,您只会收到称为Boat-destructor的Boat析构函数(并且可能会丢失在Sailboat和Motorboat中分配的内存)
在查看定义后添加以下内容:
class Boat {
public:
Boat()
{ }
virtual ~Boat() // <--- this is the real catch!
{ }
...
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.