4 ms·
No, this is a bit different. This is copy-on-write-unless-we're-alone-then-just-mutate-without-copy. That is, it's possible to write without copying if it has
by nightcracker 9y ago
No, this is a bit different.
This is copy-on-write-unless-we're-alone-then-just-mutate-without-copy. That is, it's possible to write without copying if it has been determined that there are no other readers that would be referring to the old value (thus no copy is needed).
- slavik81 9y agoThat's exactly what the Qt collections do: > Implicit sharing automatically detaches the object from a shared block if the object is about to change and the reference count is greater than one. (This is often called copy-on-write or value semantics.) [source: http://doc.qt.io/qt-5/implicit-sharing.html http://doc.qt.io/qt-5/implicit-sharing.html] The C++ language is sometimes a little cruel, though. It's easy to accidentally call the mutable version of a function when the const version would have been sufficient. That can be a performance problem if it causes unnecessary copies.
- pavanky 9y agoThat is a natural extension of copy on write if you are keeping reference counts. I implemented something similar for a C++ library a couple of years ago.
- barrkel 9y agoIt's what Delphi has been doing with strings since 1995. It really is just copy on write, which normally has an assumption that the thing is shared before you copy. It's easily implemented with a refcount. It makes heap allocated types behave a lot like value types.
- jcelerier 9y ago> copy-on-write-unless-we're-alone-then-just-mutate-without-copy well, yes, that's generally called copy-on-write. A COW class which does a copy every time you write to it would be pretty useless, woudln't it ? e.g. if you did, in old std::strings: std::string s = "foo"; s[1] = "x"; // no copy here auto s2 = s; // no copy here; s[1] = "y"; // s is copied in a new buffer s[1] = "z"; // no copy here s2 += "bar"; // no copy here