Re: Why C++ is vastly superior to C
Stefan Ram <ram@zedat.fu-berlin.de> wrote:
This seems to be due to the string being passed by value,
so that it will be copied?
That's not the point. It doesn't matter if the string is returned by
value, or via a reference/pointer given to the function as parameter:
Encapsulation is still maintained and freeing the resource is not
transferred to the calling code.
But wouldn't it be more efficient to pass such a possibly
large object by a pointer or reference, which also saves
time for allocation and deallocation? And when doing so,
will it still be true that one does not have to worry?
In this particular case most compilers will use return value optimization,
which means that the function constructs the return value right on the
caller's stack rather than on its own. Thus the copying will be averted.
(A copy might be triggered in the calling code, depending on the situation
and how the function is being called, but that's another issue.)
If large containers are being passed by value a lot in the program,
you could implement a copy-on-write wrapper around them. The nice thing
is that the exact method by which the copying is done is inconsequential
in the code that uses it.