Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap a plain buffer of char's with an std::string or an equivalent thereof?

Motivation:

I'm using some library (which I don't control) with the following function:

char* foo(/*some parameters here */);

Which returns a very long, null-terminated string. Now, I want to use the function

void bar(const std::string& s);

which is available in another library I'm using (that is, I don't control the signatures of either of these functions). I want to pass the result of foo() to bar() - without copying it.

Question:

I want to wrap a contiguous buffer of characters with a string object, so it can be passed as a const std::string&. How can I do this?

Notes:

  • I realize this may be frowned upon, but I'd like to do it anyway, if it's possible.
  • Yes, this may be inappropriate, or ugly, or too C-like - but it's what I (think I) need to do.
  • Comments on answers suggest that inheriting std::string is not an option, as it doesn't have the appropriate virtual methods. That basically leaves us with assuming things about the implementation (or writing different code for different implementations), and 'hand-constructing' an std::string instance. Thus, the question seems to be about doing that.
like image 446
einpoklum Avatar asked Dec 25 '22 09:12

einpoklum


1 Answers

No, you can't. Review your requirements and eliminate the need for this.

like image 193
Christian Hackl Avatar answered Dec 28 '22 10:12

Christian Hackl