Home > Backend Development > C++ > body text

How to Implement the `make_unique` Function in C 11 for Compilers Lacking Native Support?

DDD
Release: 2024-10-28 02:18:30
Original
449 people have browsed it

How to Implement the `make_unique` Function in C  11 for Compilers Lacking Native Support?

Implementing the make_unique Function in C 11

In C 11, the make_unique function is used to create unique_ptr objects. It provides a convenient way to allocate memory and manage the lifetime of objects. For those whose compilers do not support the make_unique function, a custom implementation can be created.

To write the make_unique function, we can use the unique_ptr constructor that takes a raw pointer as an argument. The following template code shows how to implement the make_unique function:

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

This implementation uses std::forward to pass the arguments to the T constructor, ensuring that perfect forwarding is preserved.

For compilers that support it, a more sophisticated implementation can be found in sasha.sochka's answer, which also supports the creation of unique_ptr objects from arrays. However, if sasha.sochka's solution does not compile with your compiler, the above implementation should work effectively.

The above is the detailed content of How to Implement the `make_unique` Function in C 11 for Compilers Lacking Native Support?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!