简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM