Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way make a std::string that references an externally provided buffer but not own it?

Basically if one has a preloaded buffer for a null terminated string and the length to be referenced, and wants to pass a reference to it into a method that takes a std::string & but not copy the string or have it owned, is it possible to do so ?

This would only have a limited lifespan that is managed in such a way that it is only valid while the buffer is valid.

like image 929
peterk Avatar asked Jan 27 '26 21:01

peterk


1 Answers

Is there a way make a std::string that references an externally provided buffer but not own it?

No.

You have these options:

  1. Use std::string as the "external" buffer in the first place.
  2. Copy the external buffer into the string.
  3. Don't use (reference to) std::string as the parameter.
    • std::string_view is a typically good choice. However, it's very easy to create non-null terminated string views, and your premise explicitly states null termination. If that's important, then you may need to avoid string view.
    • If string view isn't appropriate, then you can use const char* to point to the null terminated string.
like image 54
eerorika Avatar answered Jan 30 '26 10:01

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!