Home > Backend Development > C++ > How to Implement the make_unique Function in C 11?

How to Implement the make_unique Function in C 11?

DDD
Release: 2024-10-30 13:26:02
Original
707 people have browsed it

How to Implement the make_unique Function in C  11?

Implementing the make_unique Function in C 11

Despite its omission from certain compilers, the make_unique function remains a vital tool for managing memory. Here's how to replicate its functionality in C 11:

<code class="cpp">template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
    // Allocate the object on the heap with the provided arguments
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}</code>
Copy after login

This implementation utilizes std::forward to ensure perfect forwarding of the arguments to the constructor of the object being managed by the unique pointer.

For compilers that lack make_unique support, such as VC2012, this custom implementation provides an effective alternative. However, if your compiler supports the answer provided by sasha.sochka, that solution is more robust and handles arrays as well.

The above is the detailed content of How to Implement the make_unique Function in C 11?. 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