哪一种是在C 中分配非初始化内存的最惯用方法

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

本文关键字:内存 方法 初始化 分配 哪一种      更新时间:2023-10-16

选项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优化 Reallocations ,而operator new/delete(Realloc不是一个简单的免费 malloc)。/p>