Ah, another round with learning about smart pointers! Luckily, this study revealed that much progress has been made in C++11 and C++14 since the previous text that told me I had to make my own shared_ptr.
Step 1: Unique_ptr is good for exclusive ownership, and great for pointer-to-implementation (Pimpl, heh) idioms!
Step 2: Shared_ptr is now a legitimate part of the standard. Just be careful that the shared_ptr keeps track and doesn't leave dangling pointers (by way of cycled references and what not)
Step 3: And in the case of said cyclical references, use weak_ptr for its keen ability to detect whether it dangles!
Step 4: Use make_shared and make_unique over duplicate code and allocation by constructing based off a new constructed object. It's just more efficient that way (except for weak_ptrs that get destroyed after shared_ptrs)
Step 5: When using the Pimpl idiom, make sure to declare special member functions BUT put them implemented in the implementation file.
Step 6: std::move and std::forward actually do nothing like it says; it just makes something that could be eligible for moving by unconditional and conditional rvalue casting. Move is simpler, but forward is more correct for rvalue casting.
Step 7: Keep const member functions thread safe! Use atomics for singular values/memory locations, but for anything else, nothing works better than a mutex.
Step 8: Constexpr is a good way to keep values const and known during compilation, while it allows functions to produce constexpr return values and function regularly with normal values
Step 9: Declaring noexcept is a good idea for things that don't emit exceptions (std::pow, swap, moves) to help optimize the calls for those functions.
Nearly done! Just a couple more days.
No comments:
Post a Comment