Re: Best practice: return by value versus const ref
On 06.10.2012 02:40, Nobody wrote:
On Fri, 05 Oct 2012 17:33:44 +0200, Marcel M??ller wrote:
taking into account that many (almost all?) std::string implementations
provide a copy constructor with O(1) together with copy on write,
Not any more. That used to be common until multi-threading started
being widely used, at which point the overhead of locking every access
outweighed the advantages of CoW. It might still be used on platforms
which have separate single-threaded and multiple-threaded versions of the
standard library. But in general, you should assume that string copies are
O(n).
Hmm, that's a pity.
It confirms my behavior not to use std::string and to prefer other
immutable string implementations that can be copied by reference.
Unfortunately something like that is not part of he standard.
I do not care much about the memcpy for a usually small string content,
but over and over using allocators might be an impact and is subject to
some kind of synchronization too - at least at the delete operation.
In fact, CoW only needs a few synchronization points. Firstly at the
copy constructor, secondly when a non-unique reference is detached from
a string instance. Both can be implemented lock free with atomic
increment/decrement. And if you use an inner and an outer reference
count, most of the atomic increments at copy construction can also be
avoided at the cost of some more logic when detaching from references
with higher outer count.
Marcel