从函数返回一个唯一的空指针

11

要从C语言函数中获取void *类型的返回值,可以像下面这样做(非常基础的示例):

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

当使用std::unique_ptr<>时,我如何实现相同的结果?


https://dev59.com/92855IYBdhLWcg3wfURM - dragosht
1
请解释一下你在处理它时遇到了什么问题。 - molbdnilo
1
请参考此答案获取通用的void unique_ptr:https://dev59.com/questions/IFkS5IYBdhLWcg3w6qXU#39288979 - VLL
请注意,在C++中几乎没有理由像这样使用malloc。您正在返回指向原始内存的指针,需要在使用之前将其放置到新对象中。如果您没有很好的理由在分配内存时创建对象,则应使用newstd::make_unique,它们将分配内存并创建适当的对象。在任何情况下,使用带有reservestd::vector可能更好。即使您不使用这些,operator new也是分配内存的惯用方式,而不是malloc - walnut
3个回答

20

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

3
使用std::free直接作为删除器对@RealFresh答案的简化:
auto get_ptr(std::size_t size) {
    return std::unique_ptr<void, decltype(&std::free)>(std::malloc(size), std::free);
}

请看我对问题的评论。

1
考虑返回指向char数组的指针:
#include <memory>

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接