Memory management of C libraries in C++ -- Kevin Dungs

In the "better C than C" department:

Memory management of C libraries in C++

by Kevin Dungs

From the article:

Today I had some time to play around with libgit2, an excellent C-library for Git. But since I was thinking about using it together with the freshly released Proxygen, the fast HTTP-framework from Facebook, I wanted to use the library functions from C++ from the start.

This was a perfect opportunity to play around with C++ memory management objects in the context of a C-library...

Add a Comment

Comments are closed.

Comments (1)

0 0

Cap'n Rotbart said on Dec 5, 2014 11:51 AM:

    using uniqueRepositoryPtr = std::unique_ptr<
git_repository, decltype(&git_repository_free)>;
git_repository *rawRepo = nullptr;
git_repository_open(&rawRepo, "./testrepo");
uniqueRepositoryPtr repo{std::move(rawRepo), git_repository_free};

A small helper may reduce this by a line or two. Something like

template <typename T, typename DeleterT>
struct uptr_mover
{
using unique_ptr = std::unique_ptr<T, DeleterT>;

uptr_mover(unique_ptr& u) : u_ptr{&u} {}

operator T**()
{
return &c_ptr;
}

~uptr_mover()
{
if (u_ptr->get() != c_ptr) // Prevents double assign / self-reset
u_ptr->reset(c_ptr);
}

T* c_ptr;
std::unique_ptr<T>* u_ptr;
};

template <typename T, typename DeleterT>
uptr_mover<T, DeleterT> move_into_unique_ptr(std::unique_ptr<T, DeleterT>& u) // Perhaps questionable naming
{
return uptr_mover<T, DeleterT>{ u };
}

would make this

std::unique_ptr<git_repository, decltype(&git_repository_free)> repo{0, git_repository_free};
git_repository_open(move_into_unique_ptr(repo), "./testrepo");

Also, wrapping the *_free functions in functors may help further - no need for both git_repository_free and decltype(&git_repository_free).