Reputation: 11000
The title says it.
I have tried:
new char[nSize];
but it can return uninitialized memory.
where as calloc
ensures a zero-initialization.
I could call memset, etc. - but isn't there a more direct way ?
Upvotes: 2
Views: 451
Reputation: 238401
What's the most suitable c++ replacement of calloc?
For most purposes, std::vector
. Or std::string
if you intend to represent a character string. It will automatically delete whatever memory it allocates.
For data structures that contain many arrays that are not mutually contiguous, you might want to avoid the slightly-larger-than-pointer size of std::vector
, and instead might opt for unique pointer:
auto ptr = std::make_unique<char[]>(nSize);
You can use value initialisation with a new expression as well. This is what std::make_unique
does internally:
new char[nSize]();
But I would not recommend allocations without a RAII container.
As mentioned by geza, calloc
may be optimised (on some systems) such that it may elide setting the memory to zero when allocating a large block. If such optimisation applies to your case, and is measurably significant, then there may be an argument for using std::calloc
in C++.
Upvotes: 4