Question

I use calloc, I've read that, calloc internally calls new handler, so what should I go for?

Should I use new operator(which allocate fast) or calloc(which can allocate and initialize memory as well)?

Était-ce utile?

La solution 2

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.

Autres conseils

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. I.e. new does much more than calloc.

In C++, if you feel that you need to allocate some memory for e.g. some variable-sized array, consider using the standard containers first, e.g. 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);

Should I use new operator(which allocate fast) or calloc(which can allocate and initialize memory as well)?

In C++ you should never use *alloc memory function (malloc, calloc, free, etc). They lead you to create code that is unsafe for C++ (for C it is fine).

You should also use most specialized (higher level) code constructs whenever available.

That means:

  • prefer new/new[]/delete/delete[] over malloc/calloc/free
  • prefer smart pointers over raw pointers
  • prefer abstractions over raw pointer data (i.e. use std::vector/std::array/etc instead of new[] and delete[], use std::unique_ptr<T>/std::shared_ptr<T> instead of T*, etc.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top