Skip to content

Instantly share code, notes, and snippets.

@evakili
Last active March 15, 2024 02:13
Show Gist options
  • Save evakili/a1b9fd65c496046dcd24 to your computer and use it in GitHub Desktop.
Save evakili/a1b9fd65c496046dcd24 to your computer and use it in GitHub Desktop.
A generic unique_ptr with malloc/free
#ifndef MALLOC_UNIQUE_PTR_H
#define MALLOC_UNIQUE_PTR_H
/*
idea borrowed from http://www.codeproject.com/Articles/820931/Using-std-unique-ptr-RAII-with-malloc-and-free
*/
#include<memory>
template<typename T>
using malloc_unique_ptr = std::unique_ptr<T, decltype(std::free)*>;
template<typename T>
inline malloc_unique_ptr<T> make_malloc_unique(size_t sz) {
return malloc_unique_ptr<T>{ reinterpret_cast<T*>(std::malloc(sizeof(T) * sz)), std::free) };
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment