In C 11, there is no built-in std::make_unique function, which would allow for concise instantiation of unique pointers. Developers found the syntax
std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
to be unnecessarily verbose and proposed an alternative syntax:
auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
This approach simplifies the creation of unique pointers and reduces code duplication.
The proposed implementation of std::make_unique employs perfect forwarding via std::forward to pass arguments to the constructor. Perfect forwarding ensures that function parameters are passed in the most efficient manner, preserving their original type and value category (e.g., lvalues, rvalues).
In the make_unique implementation, the syntax
std::forward<Args>(args)...
can be interpreted as follows:
Together, they achieve perfect forwarding by ensuring that arguments are passed to the constructor with the correct value category and type.
Herb Sutter, Chair of the C standardization committee, has acknowledged the oversight of not including std::make_unique in C 11 and has indicated that it will be added in a future version. The suggested implementation is identical to the one provided in the question.
With the introduction of C 14, std::make_unique was standardized, providing the requested concise syntax for creating unique pointers.
The above is the detailed content of How Does `std::make_unique` Achieve Perfect Forwarding in C ?. For more information, please follow other related articles on the PHP Chinese website!