fenbf / cppstories-discussions

4 stars 1 forks source link

2021/smart-ptr-ref-card/ #57

Open utterances-bot opened 3 years ago

utterances-bot commented 3 years ago

C++ Smart Pointers Reference Card - C++ Stories

Smart pointers available since C++11 are an essential foundation for writing secure code in Modern C++. Thanks to RAII (Resource Acquisition Is Initialization), they allow you to work with pointers to allocate memory or other managed objects efficiently. This blog post will show you the core points for working with those handy types.

https://www.cppstories.com/2021/smart-ptr-ref-card/

2kaud commented 3 years ago

"unique_ptr is movable only, so it should be passed with std::move to explicitly express the ownership transfer:"

It can also be passed by ref.

fenbf commented 3 years ago

maybe I should expand this section, for example we have: C++ Core Guidelines - R.33: Take a unique_ptr& parameter to express that a function reseats thewidget

2kaud commented 3 years ago

Possibly there is sometimes an issue re 'ownership'. I found that using dynamic memory was taught as "you need to use new. When you no longer need the memory then you can use delete/delete [].

Remembering to use delete {[]} to the right place(s) is a pain and can introduce issues, so use std::unique_ptr/std::shared_ptr. You don't now need to worry about delete {[]} - this will be done for you.

You can't pass a std::unique_ptr by value so pass it by ref and you'll be all right.

It can awkward to use std::unique_ptr so there's std::make_unique to make things even easier"

Nowhere in this is this concept of ownership explained. Nowhere about passing the std::unqiue_ptr by pointer to its data if ownership isn't required to be passed. Passing a pointer as an argument to a function seems to be under-used once std::unique_ptr is known. Just pass std::unique_ptr by ref and don't sweat the details...