C++ pointers simple question
If I have the following lines inside a loop:
Type *unite开发者_运维百科 = new Type(newSize);
or
double *array= new double[anySize];
what is the behavior in what concerns to memory if I don't have delete operators inside it? It will be constantly allocating objects and arrays on different memory locations, and therefore memory leaks?
Yes it will. This:
for (int i = 0; i < 10; ++i)
{
Type* unite = new Type(newSize);
}
will allocate 10 objects of type Type
, all at different locations. None of them will be deallocated, and at the end you will not have a pointer to any of them. You will leak 10 * sizeof(Type)
bytes of memory.
Similarly, this
for (int i = 0; i < 10; ++i)
{
double *array= new double[anySize];
}
will for the same reason leak 10 * anySize * sizeof(double)
bytes of memory.
It will be constantly allocating objects and arrays on different memory locations, and therefore memory leaks?
Assuming you mean this:
for (;x;x)
{
double *ptr = new double[42];
}
Then the answer is yes, the memory is leaked.
Yes. You will leak memory at every iteration of your loop. boost::scoped_ptr
and boost::scoped_array
are made to handle such situations.
精彩评论