3 ms·
You're missing out in a big way. std::unique_ptr & std::shared_ptr are amazing. If you're still writing new & delete, you're just making things harder on yours
by kllrnohj 6y ago
You're missing out in a big way.
std::unique_ptr & std::shared_ptr are amazing. If you're still writing new & delete, you're just making things harder on yourself. I'll still use raw pointers in C++, but only the a borrowing context. It massively simplifies ownership. No more reading docs to try and guess if this pointer being passed in or returned needs to be freed or not. If I own it, it's a unique_ptr. If I'm giving it to someone else, it's a unique_ptr&&. If I'm letting something borrow it, it's a raw pointer or reference.
Or I'll make my own smart pointer containers for allocations with special lifecycles, like per-frame allocations from a custom arena allocation that must not be destroyed with delete/free.
Why try to remember all your lifecycle manually, which is incredibly error prone and no you're not immune to mistakes here, when you can compiler-enforce it instead?
- whimsicalism 6y agoIn a borrow context, what makes a raw pointer preferable to a weak_ptr or shared_ptr& (or a plain old reference if you don't want it to be optional)?
- kllrnohj 6y agoweak_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 }
- nemetroid 6y agoTo have either weak_ptr or shared_ptr& you need to have a shared_ptr to begin with. Unless you actively want shared ownership, there's little reason to use shared_ptr.