我有一个创建一些Foo并将其添加到Foos vector 的方法。敌人负责在销毁期间删除其酒吧。 Foo构造函数采用Bars的指针及其大小。当函数返回时,本地Foo被删除并销毁其Bars,但是我得到了一个有效的Foo对象。
我应该如何更正确地处理呢?我应该以其他方式管理酒吧吗?我应该让构造函数复制数组吗?我可能会拥有成千上万的酒吧。
尚未尝试对此进行编译,这只是正在发生的事情的一个示例。
class Bar
{
public:
Bar(){}
~Bar(){}
int a;
int b;
int c;
};
class Foo
{
private:
Bar * myBars;
int size;
public:
Foo(Bar * myBars, int size)
{
this->myBars = myBars;
this->size = size;
}
Bar * getBars()
{
return myBars;
}
int getSize()
{
return size;
}
~Foo()
{
if(myBars != NULL)
{
if(size == 1)
{
delete myBars;
}
else if(size > 1)
{
delete [] myBars;
}
}
}
};
void doIt(std::vector<Foo> & foos)
{
Bar * myBars = new Bar[4];
//Pretend we initialize the Bars...
Foo foo(myBars);
foos.push_back(foo);
//local foo gets deleted
}
int main()
{
std::vector<Foo> foos;
doIt(foos);
Bar * myBars = foos[0].getBars();
int size = foos[0].getSize();
//Do something with myBars
return 0;
}
最佳答案
与Bars类似,您也可以在堆上创建Foo对象,以避免在doIt函数中破坏它。如果Foo对象是动态分配的,则不会在doIt()函数返回时销毁它。
您可以像下面那样清理所有的Foo和Bar对象(工作代码)
#include <vector>
using namespace std;
class Bar
{
public:
Bar(){}
~Bar(){}
int a;
int b;
int c;
};
class Foo
{
private:
Bar * myBars;
int size;
public:
Foo(Bar * myBars, int size)
{
this->myBars = myBars;
this->size = size;
}
Bar * getBars()
{
return myBars;
}
int getSize()
{
return size;
}
~Foo()
{
if(myBars != NULL)
{
if(size == 1)
{
delete myBars;
}
else if(size > 1)
{
delete [] myBars;
}
}
}
};
void doIt(std::vector<Foo *> & foos)
{
Bar * myBars = new Bar[4];
//Pretend we initialize the Bars...
Foo *pFoo = new Foo(myBars, 4);
foos.push_back(pFoo);
}
int main()
{
std::vector<Foo *> foos;
doIt(foos);
Bar * myBars = foos[0]->getBars();
int size = foos[0]->getSize();
for(int i = 0;i < foos.size(); i++)
{
delete foos[i];
}
foos.clear();
return 0;
}