【问题标题】:Which one is the most idiomatic way to allocate uninitialized memory in C++哪一种是在 C++ 中分配未初始化内存的最惯用的方法
【发布时间】:2018-03-09 08:57:36
【问题描述】:

选项 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++ 中使用哪个更好/更惯用。

【问题讨论】:

  • @FrançoisAndrieux:std::aligned_storage 不分配内存
  • @geza 是的。我评论的重点是建议分配 std::aligned_storage 的实例而不是原始内存。该示例表明我们知道内存应该足够大以容纳一些T 类型的对象。这是便携式解决方案。
  • @FrançoisAndrieux - malloc 被定义为已经分配内存“适合任何内置类型”。同样,operator newdefined 为:“返回的指针应适当对齐,以便它可以转换为任何完整对象类型的指针”。
  • @FrançoisAndrieux:std::aligned_storage 不是主要用于未分配的东西吗? operator new 是否使用有关它分配的类型的信息?例如,它在分配存储时是否使用对齐信息?

标签: c++ memory malloc new-operator


【解决方案1】:

如果可能,您应该更喜欢以类型安全的方式分配内存。如果这不成问题,请选择选项 A,operator new(size_t, std::nothrow),因为:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-11
    • 2018-02-18
    • 1970-01-01
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-08
    相关资源
    最近更新 更多