3 ms·
weak_ptr is a complete different thing, but the meaningful difference between a raw pointer or a shared_ptr& or unique_ptr& is it avoids leaking irrelevant deta
by kllrnohj 6y ago
weak_ptr is a complete different thing, but the meaningful difference between a raw pointer or a shared_ptr& or unique_ptr& is it avoids leaking irrelevant details into the function signature. If the function is only borrowing, it doesn't care about the overall lifetime management (that is, if it's shared, unique, or custom), so that detail shouldn't be part of the function signature.
It also needlessly prevents the function from working in both shared_ptr & unique_ptr contexts.
Same thing for plain old references, although I tend to stick to pointers if the function is mutating as it makes that clearer at the callsite.
- whimsicalism 6y agoThat makes sense to me. Why does a pointer imply mutation? I thought that was what const is meant to signal.
- ericbarrett 6y agoIt's convention in C++ to pass-by-pointer if the function will mutate the argument. The other way, by (non-const) reference, is discouraged because the function invocation looks the same as the extremely common pass-by-value case. void ptr_add(int *f) { *f += 5; } void val_add(int f) { f += 5; // only changes local copy of f } void ref_add(int &f) { f += 5; } int main() { int foo = 42; ptr_add(&foo); // foo is now 47 val_add(foo); // foo is still 47 ref_add(foo); // foo is now 52 }