Home > Backend Development > C++ > Why is `std::make_unique` Missing in C 11, and How Does Perfect Forwarding Work in its Implementation?

Why is `std::make_unique` Missing in C 11, and How Does Perfect Forwarding Work in its Implementation?

DDD
Release: 2024-12-30 00:30:12
Original
584 people have browsed it

Why is `std::make_unique` Missing in C  11, and How Does Perfect Forwarding Work in its Implementation?

Make_unique and Perfect Forwarding

Q: Why is the centralized make_unique function missing in the C 11 standard library?

Many find the construction boilerplate for unique pointers inconvenient. For example:

std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
Copy after login

A sleek function like this would be preferred:

auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
Copy after login

Q: Here's a make_unique implementation attempt, but something about the std::forward appears broken. What is it doing and how is it supposed to be used?

template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
Copy after login

A: The omission of std::make_unique in C 11 was acknowledged as an oversight: it was added in C 14.

The std::forward(args) expression employs perfect forwarding to produce an artificial reference to the arguments ...args, allowing them to be forwarded to the new expression in T(std::forward(args)...) and unify the construction behavior for lvalues and rvalues.

The above is the detailed content of Why is `std::make_unique` Missing in C 11, and How Does Perfect Forwarding Work in its Implementation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template