I've been looking into this for the past few days, and so far I haven't really found anything convincing other than dogmatic arguments or appeals to tradition (i.e. "it's the C++ way!").
If I'm creating an array of objects, what is the compelling reason (other than ease) for using:
#define MY_ARRAY_SIZE 10
// ...
my_object * my_array=new my_object [MY_ARRAY_SIZE];
for (int i=0;i<MY_ARRAY_SIZE;++i) my_array[i]=my_object(i);
over
#define MEMORY_ERROR -1
#define MY_ARRAY_SIZE 10
// ...
my_object * my_array=(my_object *)malloc(sizeof(my_object)*MY_ARRAY_SIZE);
if (my_object==NULL) throw MEMORY_ERROR;
for (int i=0;i<MY_ARRAY_SIZE;++i) new (my_array+i) my_object (i);
As far as I can tell the latter is much more efficient than the former (since you don't initialize memory to some non-random value/call default constructors unnecessarily), and the only difference really is the fact that one you clean up with:
delete [] my_array;
and the other you clean up with:
for (int i=0;i<MY_ARRAY_SIZE;++i) my_array[i].~T();
free(my_array);
I'm out for a compelling reason. Appeals to the fact that it's C++ (not C) and therefore malloc
and free
shouldn't be used isn't -- as far as I can tell -- compelling as much as it is dogmatic. Is there something I'm missing that makes new []
superior to malloc
?
I mean, as best I can tell, you can't even use new []
-- at all -- to make an array of things that don't have a default, parameterless constructor, whereas the malloc
method can thusly be used.
If you do not want to get your memory initialized by implicit constructor calls, and just need an assured memory allocation for placement new
then it is perfectly fine to use malloc
and free
instead of new[]
and delete[]
.
The compelling reasons of using new
over malloc
is that new
provides implicit initialization through constructor calls, saving you additional memset
or related function calls post an malloc
And that for new
you do not need to check for NULL
after every allocation, just enclosing exception handlers will do the job saving you redundant error checking unlike malloc
.
These both compelling reasons do not apply to your usage.
which one is performance efficient can only be determined by profiling, there is nothing wrong in the approach you have now. On a side note I don't see a compelling reason as to why use malloc
over new[]
either.