J
Jeff Williams
Ok, everyone loves to talk about dynamic arrays and ptr's etc, they provide
endless conversation so here goes:
Will this leak memory (my intuition says yes):
void foo(vector<int*>& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(pInts);
}
// It can be assumed that later on in the program vec will have
// delete called on each individual element
This example is to simulate a technique I am using involving more
complicated stuff so yes I realize there are better ways to do the above in
this simple case.
But also I will explain what I am trying to do in the bigger picture in case
anyone wishes to make suggestions.
I want to fill a container (a vector but it shouldnt matter what) with ptr's
to instances of objects. But there will be millions of these objects and I
wish to allocate them all at once and add them to the container. The
calling code doesn't really know the exact type of the object that will go
into the container, it only knows they will at least derive off the type of
the ptr in the container. BUT in reality they will all be the same object,
which is why i want to allocate them all at once... for speed and to avoid
fragmenting memory.
So the obvious solution of something like:
vector<basePtr*> vec;
vec.reserve(1000000);
for(int i = 0; i < 1000000; ++i)
{
basePtr* pOb = CreateObject(); // virtual func
vec.push_back(pOb);
}
isn't the solution I want
Jeff
endless conversation so here goes:
Will this leak memory (my intuition says yes):
void foo(vector<int*>& vec)
{
int* pInts = new int[100];
for(int i = 0; i < 100; i++)
vec.push_back(pInts);
}
// It can be assumed that later on in the program vec will have
// delete called on each individual element
This example is to simulate a technique I am using involving more
complicated stuff so yes I realize there are better ways to do the above in
this simple case.
But also I will explain what I am trying to do in the bigger picture in case
anyone wishes to make suggestions.
I want to fill a container (a vector but it shouldnt matter what) with ptr's
to instances of objects. But there will be millions of these objects and I
wish to allocate them all at once and add them to the container. The
calling code doesn't really know the exact type of the object that will go
into the container, it only knows they will at least derive off the type of
the ptr in the container. BUT in reality they will all be the same object,
which is why i want to allocate them all at once... for speed and to avoid
fragmenting memory.
So the obvious solution of something like:
vector<basePtr*> vec;
vec.reserve(1000000);
for(int i = 0; i < 1000000; ++i)
{
basePtr* pOb = CreateObject(); // virtual func
vec.push_back(pOb);
}
isn't the solution I want
Jeff