B是来自A的派生类。C是一个寄存器类,其中包含A和B对象的数量未知数。尽管删除了它们,但仍检测到内存泄漏
我定义了三个类,因为它们可以向下看到。 B是来自A的派生类。C是一个寄存器类,其中包含A和B对象的数量未知数。因此,我正在使用动态分配的指针数组,该数组将存储每个动态分配的对象的引用。例如,我创建了一个两个成员的集合,并在输出上打印了成员变量。尽管将它们删除(首先是对象,然后是指针数组),但仍检测到内存泄漏。我能得到一些帮助,因为我真的看不到我在做错什么?
#include <iostream>
#include <string>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
class A {
protected:
int a;
public:
A(int pa) { a = pa; }
A(const A& theOther) { this->a = theOther.a; }
virtual void print() const { cout << a << endl; }
};
class B: public A {
protected:
int b;
public:
B(int pa, int pb): A(pa), b(pb) {}
B(const B& theOther): A(theOther.a), b(theOther.b) {}
void print() const {
A::print();
cout << b << endl;
}
};
class C {
public:
unsigned elementNum;
A** pData;
void createCollection() {
cin >> elementNum;
pData = new A * [this->elementNum];
}
~C() {
for (unsigned i = 0; i < this->elementNum; i++) {
delete pData[i];
}
delete[] pData;
}
};
int main(void) {
C REG;
REG.createCollection();
REG.pData[0] = new A(2);
REG.pData[1] = new B(3, 4);
REG.pData[0]->print();
REG.pData[1]->print();
_CrtDumpMemoryLeaks();
return 0;
}
I've defined three classes, as they can be seen downwards. B is a derived class from A. C is a register class containing A and B objects in an unknown amount. For this reason, I'm using a pointer array dynamically allocated that will store each dynamically allocated object's reference. For example, I created a two-member collection, and printed out the member variables on the output. Despite deleting them (objects first, then the pointer array) afterwards, memory leak is still detected. Can I get some help, cause I really don't see what I'm doing wrong?
#include <iostream>
#include <string>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
using namespace std;
class A {
protected:
int a;
public:
A(int pa) { a = pa; }
A(const A& theOther) { this->a = theOther.a; }
virtual void print() const { cout << a << endl; }
};
class B: public A {
protected:
int b;
public:
B(int pa, int pb): A(pa), b(pb) {}
B(const B& theOther): A(theOther.a), b(theOther.b) {}
void print() const {
A::print();
cout << b << endl;
}
};
class C {
public:
unsigned elementNum;
A** pData;
void createCollection() {
cin >> elementNum;
pData = new A * [this->elementNum];
}
~C() {
for (unsigned i = 0; i < this->elementNum; i++) {
delete pData[i];
}
delete[] pData;
}
};
int main(void) {
C REG;
REG.createCollection();
REG.pData[0] = new A(2);
REG.pData[1] = new B(3, 4);
REG.pData[0]->print();
REG.pData[1]->print();
_CrtDumpMemoryLeaks();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论