Skrevet av Emne: C++ unique_ptr wrapper for strdup()  (Lest 10224 ganger)

Utlogget Floyd-ATC

  • Livstidsdiktator
  • Administrator
  • Guru
  • *****
  • Innlegg: 542
  • Karma: +12/-0
    • MSN Messenger - floyd@atc.no
    • Vis profil
    • floyd.atc.no
    • E-post
C++ unique_ptr wrapper for strdup()
« på: 29. ſeptember 2020, 11:48 am »
  • [applaud]0
  • [smite]0
  • How to wrap a char* from strdup() in a smart pointer to guarantee it gets freed?

    Kode: [Velg]
    #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();


    -Floyd.

    --
    Det finnes 10 typer mennesker;
    de som forstår binærtall, de som ikke gjør det, og de som forstår Grey code.

    Utlogget Beauvais

    • n00b
    • *
    • Innlegg: 1
    • Karma: +0/-3
      • Vis profil
    The best thing about comics
    « Svar #1 på: 07. November 2020, 14:35 pm »
  • [applaud]0
  • [smite]1
  • 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.