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<>
?
The malloc() and calloc() function return the void pointer, so these functions can be used to allocate the memory of any data type.
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.
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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With