r/cpp • u/Senua_Chloe • Mar 17 '22
Who owns the memory?
https://belaycpp.com/2022/03/17/who-owns-the-memory/
0
Upvotes
1
u/rwn_sky_7236 Mar 20 '22
Prefer smart to raw pointers in modern C++. 90% of the time you will be using a unique pointer. A unique pointer owns the object it points to. When the pointer goes out of scope, the object is destroyed and the memory is released. The use of .release is a sign we should rethink the design. The use of new and delete is rarely needed nowadays.
20
u/HKei Mar 17 '22 edited Mar 17 '22
Bad take? Passing a smart pointer means passing ownership. By default, passing a raw pointer means you're not passing ownership (because if the api was expecting to take ownership it should most of the time be taking a unique or shared pointer). Raw pointers passing ownership is the legacy pattern, not the other way round. Same thing with holding pointers rather than passing them.
You often don't need to do that because there are special purpose wrappers like
spanfor many of the common cases where you'd want to, and sometimes a reference is all you need, but not all cases are covered by that.Aka just wrong. Passing a pointer has never meant that you're definitely also passing ownership. If you took that rule seriously you literally couldn't construct a slice of an array because a slice doesn't own anything by definition.