Option A:
T * address = static_cast<T *>(::operator new(capacity * sizeof(T), std::nothrow));
Option B:
T * address = static_cast<T *>(std::malloc(capacity * sizeof(T)));
Context:
template <typename T>
T * allocate(size_t const capacity) {
if (!capacity) {
throw some_exception;
}
//T * address = static_cast<T *>(std::malloc(capacity * sizeof(T)));
//T * address = static_cast<T *>(::operator new(capacity * sizeof(T), std::nothrow));
if (!address) {
throw some_exception;
}
return address;
}
std::malloc
is shorter, but ::operator new
is clearly C++ and it's probably implemented in terms of std::malloc
. Which one is better / more idiomatic to use in C++.
If at all possible, you should prefer to allocate memory in a type-safe way. If that's out of the question, prefer Option A, operator new(size_t, std::nothrow)
because:
new
and delete
can be overridden legally (this can be useful in custom allocator / leak detection scenarios).set_new_handler
).The only reason to prefer malloc
/ free
is if you want to optimize reallocations with realloc
, which isn't supported by operator
new
/ delete
(realloc is not a simple free+malloc).