Ian Collins said:
Given the requirement is to copy the string, then the function wouldn't be
much use if it didn't, would it? The the actual copy of the data will
most likely not happen until the the returned value gets changed assuming
the string uses copy on write.
So the million characters (or whatever it might be), *are* copied, it just
gets delayed until a bit later (presumably just so you can claim that the
function itself is fast!). Unless of course the new string never gets
modified, in which case you can probably write a more efficient C version
too (which emulates the Python method).
So how can it be a "copy-of_in"?
It's effectively a copy for all intents and purposes. Although for this to
work, the string has to be immutable...
In all cases, assuming the resulting string needs to be modified (otherwise
there's little point in making a copy), then the 1M-char string of my
example needs to be duplicated.
(There might be a mild advantage in being able to create a 'copy' of a
string, without being sure when or if it will need duplicating.
I assume also that in the C++ example, if the original is written to or
destroyed, that that will trigger a duplication of the copy. But with
potential thousands of copies of the same string that could be in existence,
that implies quite a lot going on behind the scenes.)