【问题标题】:Returning a unique void pointer from a function从函数返回唯一的 void 指针
【发布时间】:2020-05-03 01:53:09
【问题描述】:

要从 C 中的函数中获取 void *,我会执行以下操作(非常基本的示例):

void *get_ptr(size_t size)
{
    void *ptr = malloc(size);
    return ptr;
}

使用std::unique_ptr<>时如何获得相同的结果?

【问题讨论】:

  • 请说明您在执行此操作时遇到了什么问题。
  • 查看通用 void unique_ptr 的答案:stackoverflow.com/a/39288979/2527795
  • 请注意,像这样在 C++ 中使用malloc 几乎没有理由。您正在返回一个指向原始内存的指针,您需要在允许使用它之前将新对象放置到该指针中。如果您没有充分的理由在分配内存之后创建对象,那么您应该使用newstd::make_unique 来分配内存并创建适当的对象。在任何一种情况下,std::vectorreserve 都是概率。也更好。即使你不使用这些,operator new 是分配内存的惯用方式,而不是malloc

标签: c++ c unique-ptr


【解决方案1】:

您需要指定自定义删除器才能像这样使用void 作为unique_ptr 的类型参数:

#include <memory>
#include <cstdlib>

struct deleter {
    void operator()(void *data) const noexcept {
        std::free(data);
    }
};

std::unique_ptr<void, deleter> get_ptr(std::size_t size) {
    return std::unique_ptr<void, deleter>(std::malloc(size));
}

#include <cstdio>
int main() {
    const auto p = get_ptr(1024);
    std::printf("%p\n", p.get());
}

【讨论】:

    【解决方案2】:

    考虑返回一个指向字符数组的指针:

    #include <memory>
    
    std::unique_ptr<char[]> get_ptr(std::size_t size)
    {
        return std::make_unique<char[]>(size);
    }
    

    【讨论】:

      【解决方案3】:

      使用std::free 直接作为删除器而不是构造函子来简化@RealFresh 的答案:

      auto get_ptr(std::size_t size) {
          return std::unique_ptr<void, decltype(&std::free)>(std::malloc(size), std::free);
      }
      

      不过,请参阅我对这个问题的评论。

      【讨论】:

        猜你喜欢
        • 2020-06-11
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 2014-08-16
        • 1970-01-01
        • 2018-04-06
        • 2021-10-10
        • 2011-12-06
        相关资源
        最近更新 更多