Open utterances-bot opened 2 years ago
Hi,
I was just reading your interesting article. A remark:
"How to solve those issues?
Since the object is optional, then you can also leverage std::optional. But let’s say you want to save some space in your class for that extra data (if it’s rarely created). Then you can stick to unique_ptr:
Here’s the modified version with unique_ptr @Compiler Explorer.
We also have to implement special functions in this version, but now the code is a bit shorter and much safer. No leaks are possible."
The reference to @Compiler Explorer however doesn't contain the example with unique_ptr.
@dwjbosman
hmmm... the link https://godbolt.org/z/M3rW5Pqhr contains std::unique_ptr<Data> extra_;
as a data member.
@dwjbosman - the @Complier links refer to the github page for Luke Roche?
Yea that’s me.
On Mon, Nov 8, 2021 at 08:56 JFT @.***> wrote:
@dwjbosman https://github.com/dwjbosman - the @complier https://github.com/complier links refer to the github page for Luke Roche?
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/fenbf/cppstories-discussions/issues/63#issuecomment-963173049, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC7LIQ4SMCAKRFRPDLB2CQ3UK7JJ3ANCNFSM5HSHVE5Q . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.
Note that converting unique_ptr
to shared_ptr
does not work with enable_shared_from_this<>
. If shared_from_this()
is needed, one will have to create shared pointers even for unique ownership.
In the second example, you can replace
~Package() noexcept { if (extra_) delete extra_; }
with
~Package() noexcept { delete extra_; }
since calling delete on a nullptr
is allowed and will do nothing.
6 More Ways to Refactor new/delete into unique ptr - C++ Stories
In the first part of our refactoring series, we covered (smart) pointers inside a function body; today, I’d like to show you cases for return types, data members, and a few others. Let’s jump in and replace some new() and delete! See the first part This article is the second in the series about refactoring with unique_ptr.
https://www.cppstories.com/2021/more-refactor-into-uniqueptr/