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' anstd::string
instance. Thus, the question seems to be about doing that.
std::char_traits<char>::copy
which explicitly states it's undefined if source and destination overlap. – Oftentimesstd::string
. – Aesthetics