简体   繁体   中英

Return a “const char*” as std::string& from a class method

I have a C-Libraray function returning a C-String

const char* myFuncC(struct myS *);

Now I write a class mapper:

class myC {
  private:
    struct myS * hdl
    ...
  public:
    const char* myFunc() {
      return myFuncC(hdl);
    }

  // want to have...
    const std::string& myFuncS() {
      return ??? myFuncC(hdl);
    }
}

Now I would like to return a: const std::string& and I don't want to copy the C-String pointer data

How I do this?

update

Is there a C++ Class who act like a const C++-String class and using a const C-String pointer as string source ?

I would call this class a C++-String-ExternalExternal mean … using a external source as storage… in my case a "const char *"

std::string , by definition, owns its memory and there's nothing we can do to change this. Furthermore, by returning a reference you're creating a dangling reference to a local variable (or a memory leak).

However, the idea of encapsulating contiguous character ranges in a string-like interface without copying is such a common problem that C++17 added a new type, std::string_view , to accomplish exactly that. With it, your code can be written as:

std::string_view myFuncS() {
    return {myFuncC(hdl)};
}

A string_view isn't a string but it has a very similar API and the idea is to use it instead of many current uses of string const& . It's perfect for the job here.

Note that we are returning a copy , to avoid a dangling reference. However, this does not copy the underlying memory, and is cheap — almost as cheap as returning the reference.

Simply return a new string:

std::string myFuncS() {
  return std::string(myFuncC(hdl));
}

If you really need a refence or a pointer then allocate the string on the heap and return a pointer to it:

std::unique_ptr<std::string> myFuncS() {
       return std::unique_ptr<std::string>(new std::string(myFuncC(hdl)));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM