c++ - 从函数返回唯一的 void 指针

标签 c++ c unique-ptr

获得 void *从 C 中的函数我会做这样的事情(非常基本的例子):

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

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

最佳答案

您需要指定自定义删除器才能使用 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());
}

关于c++ - 从函数返回唯一的 void 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59765957/

相关文章:

c++ - Finder 列 View 修改事件列的宽度

c - 使用realloc获得的扩展内存包含哪些内容?

c - 在 C 中实现定时、缓存攻击抵抗排序

c++ - 需要指导 : Vectors of unique_ptr to dervied classes from an abstract base class

c++ - noexcept 一个函数返回一个具有抛出析构函数的类

c++ - 函数 v8::Value::IsInt32 没有地址

c++ - TCP端口访问和C++

c++ - 无法在 CLion 中运行简单程序

c++ - unique_ptr 和指定解构函数

c++ - 返回智能指针