Search code examples
c++memorymallocnew-operator

Which one is the most idiomatic way to allocate uninitialized memory in C++


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++.


Solution

  • 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:

    • Operators new and delete can be overridden legally (this can be useful in custom allocator / leak detection scenarios).
    • Can have an alternative allocator to deal with low memory (set_new_handler).
    • Is much more C++.

    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).