4 ms·
FYI, you can use a constructor with a shared/unique ptr. auto p = unique_ptr<Foo>(new Foo()); Totally works, and may be easier to remember if you dont like th
by TFortunato 7y ago
FYI, you can use a constructor with a shared/unique ptr.
auto p = unique_ptr<Foo>(new Foo());
Totally works, and may be easier to remember if you dont like the "magic" parameter forwarding.
- jdsully 7y agoCareful with that if it's not the only thing happening in the statement. It might be a while between the 'new' and the unique_ptr ctor. If an exception happens in between the object will leak. e.g. foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y)) is a leak waiting to happen. https://stackoverflow.com/questions/37514509/advantages-of-using-stdmake-unique-over-new-operator https://stackoverflow.com/questions/37514509/advantages-of-u...
- TFortunato 7y agoVery good point! I was only thinking about the specific case of a statement that just makes an object and shoves it into a unique_ptr (e.g. does what make_unique does in the linked Herb Sutter article), in response to the comment about not being able too use a normal constructor. You are totally right that this isn't exception safe in cases like you mentioned.
- nemanjaboric 7y agoSmall note that this is fixed in C++17: https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17 https://stackoverflow.com/questions/38501587/what-are-the-ev...