首页  >  文章  >  后端开发  >  如何为缺乏本机支持的编译器实现 C 11 中的 make_unique 函数?

如何为缺乏本机支持的编译器实现 C 11 中的 make_unique 函数?

DDD
DDD原创
2024-10-28 02:18:30450浏览

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

在 C 11 中实现 make_unique 函数

在 C 11 中,make_unique 函数用于创建 unique_ptr 对象。它提供了一种分配内存和管理对象生命周期的便捷方法。对于那些编译器不支持 make_unique 函数的人,可以创建自定义实现。

要编写 make_unique 函数,我们可以使用以原始指针作为参数的 unique_ptr 构造函数。以下模板代码展示了如何实现 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>

此实现使用 std::forward 将参数传递给 T 构造函数,确保保留完美转发。

对于支持它的编译器,可以在 sasha.sochka 的答案中找到更复杂的实现,它还支持从数组创建 unique_ptr 对象。但是,如果 sasha.sochka 的解决方案无法使用您的编译器进行编译,则上述实现应该可以有效工作。

以上是如何为缺乏本机支持的编译器实现 C 11 中的 make_unique 函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn