3 ms·
What the article skips over, but is somewhat implied, is that in the case you want to pass const std::shared_ptr<Widget>&, you're not taking ownership anymore.
by reducesuffering 7y ago
What the article skips over, but is somewhat implied, is that in the case you want to pass const std::shared_ptr<Widget>&, you're not taking ownership anymore. So you should be dereferencing (outside the func rather than in) and passing const Widget& instead, because the shared_ptr isn't useful anymore and you're "breaking" the contract of shared_ptr managing it's memory. const Widget& makes it clearer you're not owning the memory in the func. There is a caveat that is mentioned in other comments about there's still a use for const std::shared_ptr<Widget>& if you're not sure whether you'll copy the Widget to a shared_ptr in the func.
- mark-r 7y agoI'm pretty sure making a copy of a shared_ptr needs to modify it, so having a const reference doesn't work.
- tlb 7y agoIt doesn't modify anything inside the shared_ptr itself, but a refcount which is pointed to by a pointer field in the shared_ptr. So you can say foo(shared_ptr<T> const &x) { saved_x = x; } and it'll update the refcount exactly once when doing the assignment.
- mark-r 7y agoThat's the problem with modern C++, you can't reason about it on general principles - you have to know way too much about implementation detail.