3 ms·
You can actually kind of do this with `std::shared_ptr` [0], but it's going to be nowhere near as efficient[1] as the Rust mechanism. Maybe a single-threaded im
by vlovich123 6y ago
You can actually kind of do this with `std::shared_ptr` [0], but it's going to be nowhere near as efficient[1] as the Rust mechanism. Maybe a single-threaded implementation of it could come close but you'd have to roll it yourself or use something like `boost::local_shared_ptr`. You may also need to go to intrusive pointers to make sure there's memory alignment.
Of course the Rust variant is not only cheaper (no ref counts), it's also guaranteed thread-safe (which again, C++ would have to use something like the atomic `shared_ptr` to achieve)
TLDR: Even when C++ can kind of do it, you have to give up concurrency safety to get close while adding memory pressure & still not being as fast while Rust gives you guaranteed concurrency safety for free regardless of accidental misuse of your API.
[0] Currently that would be constructor #8 on https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr https://en.cppreference.com/w/cpp/memory/shared_ptr/shared_p...
[1] Not only are you always paying for atomic ref counting even when you don't need it, aliased `shared_ptr` will be as expensive to take a ref for as normally constructing it - there's possible no way to `make_shared` with aliasing. This means the aliased shared_ptr will be even more expensive every time you need to access the ref count since the control block loses cache coherency. On the other hand if you structure it more carefully maybe you could vend `const std::shared_ptr<std::string>&` in your iterator so that in the single-threaded case your only overhead is constructing the aliased shared_ptr once & you leave it to the user to take a copy when transferring to another thread.
- boris 6y agoNobody in their right mind will use `shared_ptr` in this context. It will be `string_view` in and out with lifetime management left as an exercise to the programmer.
- steveklabnik 6y agoI read your parent as saying "assume we start from needing this to be checked," and then saying that this is the best that can be done. You're absolutely 1000% right that nobody would write that ever and would use string_view and not have it statically checked.
- vlovich123 6y agoThat’s exactly it. Just showing how trying to get the same safety guarantee in c++ is an either or between performance and safety.
- secondcoming 6y agoYou're over-thinking it! You don't need dynamic memory allocation and there are no concurrency issues when tokenising text.