获得 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/