To get a void * from a function in C I would do something like this (very basic example):
void *get_ptr(size_t size)
{
void *ptr = malloc(size);
return ptr;
}
How do I achieve the same result when using std::unique_ptr<>?
You need to specify custom deleter in order to use void as unique_ptr's type argument like that:
#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());
}
mallocin C++ like this. You are returning a pointer to raw memory, that you need to placement-new objects into before you are allowed to use it. If you don't have a good reason to create the objects at a later time than when you are allocating memory, then you should useneworstd::make_uniquewhich will allocate memory, as well as create appropriate objects. In either casestd::vectorwithreserveis prob. better too. Even if you don't use these,operator newis the idiomatic way of allocating memory, notmalloc.