I have a class, which contains a string as a private member. The class has public member functions which all return a const ref to a std::wstring.
All of the const-ref strings being returned are substrings of the private member.
I could store each substring as members, then return const refs to those members, but this is not optimal as it duplicates memory.
Assume that I do store enough memory to know the start and end index of each substring.
How do I implement the above class without copying any of the member string?
This is not legal, and it is not going to save you anything. std::string::substr
returns by value. That means it makes a copy of the data from the class member no matter how you return it. When you return a reference to that, you are returning a reference to a temporary local object. the const reference lifetime extensions rules wont work here and what you are left with at the call site is a dangling reference.
What you can do though is just return by value. By default this will cause a move, and the compiler can quite easily optimize this away by eliding the temporary construction directly into the object in the call site.
Another option is to have a std::string_view
member, and return sub strings from that. Doing that only costs you the copying of a pointer and a integer, so it will be quite fast.