Question

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.
Was it helpful?

Solution

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

OTHER TIPS

You can emulate it using boost::string_ref.

It has an interface that is interoperable with std::string:

boost::string_ref s = "hello world";

std::string compareto = "bye world";


bool test = (compareto != s);

Of course this will work only if you can opt to accept string_ref instead of string in your interfaces. That way, you can just pass c-strings or std::strings at leisure and it would do the right thing.

Old question, but as of C++17, you now have std::string_view, which is precisely the right tool for the job.

Simply initialise it as:

auto my_string_view = std::string_view(foo(whatever));

...and use it anywhere you'd use a std::string const. Or if you need to make a non-const copy, you can simply initialise a temporary string from it with:

auto my_new_string = std::string{my_string_view}

You can't do this, but you can easily just write your own string class. Since you are explicitly disallowing making any copies of it, you don't even need to support many of std::string-type operations, such as concatenation, etc.

(In theory, you could support concatenation without copying by creating an internal tree of buffers, but that would be more work.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top