'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.



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 eerorika