Home > Article > Backend Development > How to Implement a Custom `make_unique` Function in C 11?
The make_unique function is a convenient method for creating and managing unique pointers in C . It allows programmers to pass arguments directly to the constructor of the pointed object while ensuring that ownership is properly transferred. However, some compilers may not support make_unique natively. In such cases, it becomes necessary to implement a custom version of the function.
To implement a custom make_unique function, you can use the following code snippet:
template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); }
This custom implementation utilizes the standard library's unique_ptr and new to create a unique pointer. It forwards arguments to the constructor of the pointed object using std::forward, ensuring proper value transfer.
The custom make_unique function operates similarly to the native version. However, it may have some limitations in specific scenarios. It is worth noting that the native make_unique function added in C 14 addresses certain edge cases and optimizations that may not be present in the custom implementation.
An alternative custom implementation, which provides more versatility and handles arrays, can be found in the accepted answer by sasha.sochka on Stack Overflow:
template <typename T> std::unique_ptr<T> make_unique(T* ptr) { return std::unique_ptr<T>(ptr); } template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); }
By utilizing the provided code snippets, you can implement a custom make_unique function in C 11. While the native implementation is preferable if supported by your compiler, the custom versions discussed here offer a viable solution when necessary.
The above is the detailed content of How to Implement a Custom `make_unique` Function in C 11?. For more information, please follow other related articles on the PHP Chinese website!