Home  >  Article  >  Backend Development  >  How to Implement `make_unique` in C 11 When Your Compiler Doesn\'t Support It?

How to Implement `make_unique` in C 11 When Your Compiler Doesn\'t Support It?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 10:25:02659browse

How to Implement `make_unique` in C  11 When Your Compiler Doesn't Support It?

Recreating make_unique Function in C 11

The C 11 standard introduces a powerful function, make_unique, for creating unique pointers. However, some may encounter the issue of their compiler not supporting this function. This article provides a workaround to implement make_unique in C 11.

As per the question, the make_unique function prototype is:

<code class="cpp">template< class T, class... Args > unique_ptr<T> make_unique( Args&&&... args );</code>

The following code provides an implementation of make_unique:

<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>

This implementation uses the std::forward<> function to ensure that argument forwarding occurs correctly for all types of arguments, including references and rvalue references.

Note that if your compiler supports C 11 but not the make_unique function, you can still use this implementation as a workaround. Alternatively, if you have access to a compiler that supports C 14 or later, you can simply leverage the standard std::make_unique function for this purpose.

The above is the detailed content of How to Implement `make_unique` in C 11 When Your Compiler Doesn\'t Support It?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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