Home >Backend Development >C++ >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!