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