I’ve got a method that creates some Foo and adds it to a vector of Foos. Foos are in charge of deleting their Bars during destruction. The Foo constructor takes a pointer of Bars and a size of them. When the function returns, the local Foo gets deleted and destroys its Bars, however I get a valid Foo object back.
How should I be handling this more correctly? Should I have Bars managed some other way? Should I have the constructor copy the array instead? I am potentially going to have hundreds of thousands of Bars.
Haven’t tried to compile this, this is just an example of what is going on.
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;
}
Similar to Bars, you can create Foo objects also on the heap to avoid destruction in doIt functon. If Foo object is dynamically allocated, it will not be destroyed upon the return of doIt() function.
You can clean up all Foo and Bar objects at the end like below(Working code)