我在valgrind报告中收到此错误。
== 31766 = = 1个街区中的8个字节肯定会在825的损失记录3中丢失
我的代码如下:
struct FooList {
FooList() {}
FooList(const vector<Foo*>& fooList_): fooList(fooList_) {}
~FooList() {
BOOST_FOREACH(Foo* fooPtr, fooList) {
delete fooPtr;
}
}
vector<Foo*> fooList;
}
Foo* createFoo(bool flag)
{
if(flag) return new FooDerivedA();
else return new FooDerivedB();
}
void main()
{
FooList fl;
Foo* fooA = createFoo(true);
// some manipulation on fooA, if an exception happens at this point, the memory leaks.
fl.fooList.push_back(fooA);
Foo* fooB = createFoo(false);
// some manipulation on fooB, if an exception happens at this point, the memory leaks.
fl.fooList.push_back(fooB);
// fl's desctructor will release memory for all elements.
}
我不确定是否因为new
和delete
语句不在导致definitely lost
的同一函数中。我该如何解决这个问题?