Does std::make_unique
have any efficiency benefits like std::make_shared
?
Compared to manually constructing std::unique_ptr
:
std::make_unique<int>(1); // vs
std::unique_ptr<int>(new int(1));
ベストアンサー1
The motivation behind make_unique
is primarily two-fold:
make_unique
is safe for creating temporaries, whereas with explicit use ofnew
you have to remember the rule about not using unnamed temporaries.foo(make_unique<T>(), make_unique<U>()); // exception safe foo(unique_ptr<T>(new T()), unique_ptr<U>(new U())); // unsafe*
The addition of
make_unique
finally means we can tell people to 'never' usenew
rather than the previous rule to "'never' usenew
except when you make aunique_ptr
".
There's also a third reason:
make_unique
does not require redundant type usage.unique_ptr<T>(new T())
->make_unique<T>()
いずれの理由も、 を使用した場合のように実行時効率を向上させることには関係ありませんmake_shared
(2 番目の割り当てを回避するため、ピーク時のメモリ使用量が増加する可能性があります)。
* C++17では、これが安全でなくなることを意味するルール変更が含まれることが予想されます。C++委員会の論文を参照してください。P0400R0そして部品番号。