Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a unique void pointer from a function

Tags:

c++

c

unique-ptr

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<>?

like image 637
ZeppRock Avatar asked Jan 16 '20 08:01

ZeppRock


People also ask

Can function return void pointer in C?

The malloc() and calloc() function return the void pointer, so these functions can be used to allocate the memory of any data type.

What happens when you return a Unique_ptr?

If a function returns a std::unique_ptr<> , that means the caller takes ownership of the returned object. class Base { ... }; class Derived : public Base { ... }; // Foo takes ownership of |base|, and the caller takes ownership of the returned // object.

Can we get Typeid of void pointer?

You can use the strcmp function to help you compare const char* strings. Then after that you called GetType function, now you know to which type to convert or cast the void pointer of the Object and then do whatever you want with the current iterated object!

What is return type void pointer?

The pointer-to-void return type means that it is possible to assign the return value from malloc to a pointer to any other type of object: int* vector = malloc(10 * sizeof *vector); It is generally considered good practice to not explicitly cast the values into and out of void pointers.


2 Answers

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());
}
like image 91
Deedee Megadoodoo Avatar answered Sep 22 '22 16:09

Deedee Megadoodoo


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.

like image 41
walnut Avatar answered Sep 23 '22 16:09

walnut