Teknisk > Generelt teknisk

C++ unique_ptr wrapper for strdup()

(1/1)

Floyd-ATC:
How to wrap a char* from strdup() in a smart pointer to guarantee it gets freed?


--- Kode: ---#include <memory>
typedef std::unique_ptr<char, decltype(&std::free)> char_ptr;

char_ptr make_char_ptr(const std::string str)
{
  return char_ptr(strdup(str.data()), std::free);
}

//...

char_ptr foo = make_char_ptr("bar");
foo.get(); // char* pointer to a copy of "bar"

// pointer automatically gets freed when 'foo' goes out of scope
// or can be freed manually with
foo.reset();

--- Slutt kode ---

Beauvais:
The best thing about comics is that a comic creator can control when and where the reader sees exciting things in the comic. These exciting moments in the comic are generally placed after the turn of a page To Know More.

Navigering

[0] Oversikt

Skift til full visning