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.
Basically, the answer is no for the non owning string.
However, if the non owning criteria is not that important what you could do is to use your own allocator to reference a particular buffer.
What you also can do, is to use
std::pmr::stringwhich allows you to give a custommemory_resource.The idea is as following :
std::pmr::monotonic_buffer_resourceis amemory_resourceobject which continually grows. It means that a deallocation is a kind of "no op".What is nice with such a thing is that you can give the same thing to a
std::pmr::vector.However, you may pay the attention to the following points :
std::pmr::stringusechar. Since it is a trivial object, I think (I am not sure though) that it is safe to access the buffer memory after the string got destroyed. If it was a type not trivially destructible, I think it would be possible to see garbage values.