Which is more optimal: `new` or `calloc`?
This question already has an answer here:
Well, everyone's told you about new
not initialising memory etc, but they forgot about value-initialization syntax:
char *buffer = new char[size]();
So I would argue that you always use new
. If you want to initialise the memory, use the above syntax. Otherwise, drop the parentheses.
The question cannot really be answered, because it's based on the incorrect assumption that new
merely allocates memory but doesn't initialize it. The contrary is the fact:
new
not only allocates memory (unless you use "placement new"), it also calls some objects constructor. Ie new
does much more than calloc
.
In C++, if you feel that you need to allocate some memory for eg some variable-sized array, consider using the standard containers first, eg prefer
std::vector<char> buf( 1024 );
over
char *buf = new char[1024];
calloc
isn't really comparable to new
; it's closer to operator new
(they are not the same). calloc
will zero out the memory allocated whereas operator new
and malloc
won't. new
constructs an object in the storage location but calloc
doesn't.
// Using calloc:
my_object* p = static_cast<my_object*>(std::calloc(1, sizeof(my_object)));
::new(static_cast<void*>(p)) my_object(10);
// Using operator new:
my_object* p = static_cast<my_object*>(::operator new(sizeof(my_object)));
::new(static_cast<void*>(p)) my_object(10);
// using new:
my_object* p = new my_object(10);
链接地址: http://www.djcxy.com/p/78484.html
上一篇: new和malloc在c ++中的区别