简体   繁体   中英

Returning a unique void pointer from a function

To get a void * from a function in CI 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());
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM