Assuming that you prefer a faster algorithm than saving space, you could try to implement a technique called reference counting / copy-on-write yourself. The idea it to avoid copying the string unless it is absolutely necessary (for example if an edit to the string is performed).
The topic (which would be too long to explain here) is described (with an old implementation) in Scott Meyer's "More effective C++" book. Specifically there's Item 30 (Reference Counting) that will go deep down in the construction of the string in question. The whole purpose of it is to enhance algorithms like yours:
The second motivation for reference counting is simple common sense. If many objects have the same value, it’s silly to store that value more than once. Instead, it’s better to let all the objects with that value share its representation. Doing so not only saves memory, it also leads to faster-running programs, because there’s no need to construct and de- struct redundant copies of the same object value.
For the implementation you can easily use std::shared_ptr
(since C++11) or boost::shared_ptr
(prior to C++11) which provides most of the mechanism you need to reference-count the string:
std::shared_ptr<char> string(new char[n], [](int *ptr) { delete[] ptr; });
If you needn't to modify the string, (but I highly doubt that, right?), you should declare them as const char*
and avoid the reallocation.