Move constructor for std::string from char*

后端 未结 4 1154
离开以前
离开以前 2021-01-12 05:13

I have a function f returning a char*. The function documentation says:

The user must delete returned string

I wa

4条回答
  •  独厮守ぢ
    2021-01-12 06:01

    std::string steal_char_buffer( std::unique_ptr buff ) {
      std::string s = buff?buff.get():""; // handle null pointers
      return s;
    }
    std::string steal_char_buffer( const char* str ) {
      std::unique_ptr buff(str); // manage lifetime
      return steal_char_buffer(std::move(buff));
    }
    

    now you can type

    std::string s = steal_char_buffer(f());
    

    and you get a std::string out of f().

    You may want to make the argument of steal_char_buffer be a const char*&&. It is mostly pointless, but it might lead to some useful errors.

    If you can change the interface of f, make it return a std::string directly or a std::unique_ptr.

    Another good idea is to wrap f in another function that returns a std::unique_ptr or std::string:

    std::unique_ptr good_f() {
      return std::unique_ptr(f());
    }
    

    and/or

    std::string good_f2() {
      auto s = good_f();
      return steal_char_buffer( std::move(s) );
    }
    

提交回复
热议问题