哪一个是在 C++ 中分配未初始化内存的最惯用的方法

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

选项A:

T * address = static_cast<T *>(::operator new(capacity * sizeof(T), std::nothrow));

选项 B:

T * address = static_cast<T *>(std::malloc(capacity * sizeof(T)));

上下文:

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 更短,但 ::operator new 显然是 C++,它可能是根据 std::malloc 实现的。在 C++ 中使用哪个更好/更惯用。

如果可能的话,您应该更愿意以类型安全的方式分配内存。如果那是不可能的,请选择选项 A,operator new(size_t, std::nothrow) 因为:

  • 运算符 newdelete 可以被合法覆盖(这在自定义分配器/泄漏检测场景中很有用)。
  • 可以有一个替代分配器来处理低内存(set_new_handler)。
  • 更多的是 C++。

首选 malloc / free 的唯一原因是如果您想使用 realloc 优化 重新分配 ,这是不支持的通过 operator new / delete(realloc 是 not 一个简单的 free+malloc)。