【发布时间】:2010-11-11 04:05:14
【问题描述】:
我有一个 A 类型的列表指针(称为 ListA)容器一个指针 B 的向量。(每个 A 对象都是一个具有私有属性的容器类:std<vector> *B)。然后,我声明一个指针(称为C,与A具有相同的类型),通过ListA进行for循环以获取所有指针B并将它们放入C中。当我退出程序时,我先释放ListA,然后释放ListA他们自己的指针向量 B。然后我释放指针 C,但程序崩溃了。
我对此进行了一些调试,并且知道释放时指针 C 指向任何内容,因此它不知道要释放什么。
我做错了吗?或者我的问题有什么解决方案?
对不起,我会把我的代码放在下面
//Class A
#pragma once
#include "MyContainer.h"
class B;
class A
{
public:
A();
~A();
MyContainer<B> *pListOfB;
}
A::A()
{
pListOfB = new MyContainer<B>;
}
A::~A()
{
if(pListOfB)
{
delete pListOfB;
pListOfB = NULL;
}
}
//Class C
#pragma once
#include "MyContainer.h"
class B;
class C
{
public:
C();
~C();
MyContainer<B> *pListOfB;
void getListOfB(MyContainer<A> *pListOfA);
}
C::C()
{
pListOfB = new MyContainer<B>;
}
C::~C()
{
if(pListOfB)
{
delete pListOfB;
pListOfB = NULL;
}
}
void C::getListOfB(MyContainer<A> *pListOfA)
{
for(pListOfA->isBegin(); !pListOfA->isEnd();)
{
A *pA = pListOfA->getNext();
for(pA->isBegin(); !pA->isEnd();)
{
B* pB = pA->*pListOfB->getNext();
pListOfB->add(pB);
}
}
}
//Class MyContainer
#pragma once
#include <vector>
template <class T>
class MyContainer
{
public:
MyContainer(void);
~MyContainer(void);
T* getNext();
void removeAll();
void add(T* t);
void isBegin();
bool isEnd();
private:
std::vector<T*> items;
typename std::vector<T*>::iterator it;
};
template <class T> MyContainer<T>::~MyContainer()
{
removeAll();
}
template <class T> void MyContainer<T>::add(T *t)
{
items.push_back(t);
}
template <class T> void MyContainer<T>::removeAll()
{
while(!isEmpty())
{
std::vector<T*>::iterator tempIt =items.begin();
T* t = (*tempIt);
items.erase(tempIt);
delete t;
t=NULL;
}
}
template <class T>
T* MyContainer<T>::getNext()
{
if(isEnd() || isEmpty())
return NULL;
return (T*)(*(it++));
}
template <class T>
void MyContainer<T>::isBegin()
{
it = items.begin();
}
template <class T>
bool MyContainer<T>::isEnd()
{
return it==items.end();
}
我执行以下操作: 1.初始化一个列表A对象:MyContainer *pListOfA; 2.向pListOfA中的每个A对象插入B数据 3.初始C对象 4.调用C对象操作getListOfB从pListOfA中获取B数据。 5. 退出程序
程序先dealloc pListOfA,每个A再dealloc自己的pListOfB。之后程序dealloc C 对象依次dealloc c 的pListOfB 属性。但是pListOfB 指向任何内容,因为pListOfA 会dealloc 每个数据。所以我的程序崩溃了。 我通过 rem 修复了 C 类 dtor 中的 delete pListOfB 行,但我在该行收到警告内存泄漏。 这都是我的问题。请告诉我正确的方法。提前致谢。
【问题讨论】:
-
是的,你做错了什么;否则您的程序不会崩溃。但是,从上面的描述中推断出你做错了什么是非常困难的。我建议展示一个重现问题的最小程序。
-
一个
std<vector> *B?你确定吗? -
是的,没有代码,诸如“A 类型的列表指针”之类的东西真的很混乱。
-
我刚刚添加了我的简化代码。