3 ms·
Of course you should use reference counting for things that actually need to be reference counted, and there's a standard mechanism in C++ for doing this (std::
by eklitzke 4y ago
Of course you should use reference counting for things that actually need to be reference counted, and there's a standard mechanism in C++ for doing this (std::shared_ptr). However it's really only appropriate to use std::shared_ptr for things that actually have indeterminate lifetimes, because it (a) requires heap allocation and (b) requires the use of atomics. Most references/pointers in most C++ programs have simple scoping/lifetime requirements and don't require this overhead. If something retains a pointer to an object that is destroyed or goes out of scope, that can just as easily indicate that there is a logic error in the code retaining the dangling reference and therefore using std::shared_ptr or some other reference counting scheme isn't necessarily going to fix things.
C++ actually did have copy-on-write strings before C++11 (at least the std::string implementation in GCC/libstdc++ used CoW strings) but CoW implementations were made illegal because they caused a number of other problems.
- BenFrantzDale 4y agoI’ve been very pleased with Sean Parent’s `stlab::copy_on_write<T>` as a value-semantic mutable alternative to `std::shared_ptr<T>`. It has an explicit `write() -> T&` that makes it less magical than some CoW alternatives.