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

Time:02-27

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.

CodePudding user response:

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.
  • Related