Returning a unique void pointer from a function

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());
}

Consider returning a pointer to char-array instead:

#include <memory>

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

A simplification of @RealFresh's answer using std::free directly as deleter instead of constructing a functor:

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

See my comment on the question, though.

Tags:

C++

C

Unique Ptr