跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
C++ make unique
”︁(章节)
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= C++ make_unique = == 介绍 == '''make_unique''' 是 C++14 引入的一个实用函数模板,用于创建并返回一个指向新对象的 <code>std::unique_ptr</code>。它是现代 C++ 中智能指针工具集的重要组成部分,旨在提供一种更安全、更高效的方式来管理动态分配的内存,避免内存泄漏和裸指针的使用。 <code>std::make_unique</code> 的主要优势包括: * 减少显式的 <code>new</code> 和 <code>delete</code> 操作,降低内存泄漏的风险。 * 提供异常安全性,确保在构造函数抛出异常时不会泄漏内存。 * 代码更简洁,避免重复书写类型名称。 == 语法 == <code>make_unique</code> 的基本语法如下: <syntaxhighlight lang="cpp"> template< class T, class... Args > std::unique_ptr<T> make_unique( Args&&... args ); </syntaxhighlight> 其中: * <code>T</code> 是要创建对象的类型。 * <code>Args</code> 是传递给 <code>T</code> 的构造函数的参数列表。 == 基本用法 == === 创建单个对象 === 最简单的用法是创建一个动态分配的单一对象: <syntaxhighlight lang="cpp"> #include <memory> #include <iostream> struct Point { int x, y; Point(int x, int y) : x(x), y(y) {} }; int main() { auto ptr = std::make_unique<Point>(3, 4); std::cout << "Point: (" << ptr->x << ", " << ptr->y << ")\n"; return 0; } </syntaxhighlight> 输出: <pre> Point: (3, 4) </pre> === 创建数组 === <code>make_unique</code> 也可以用于创建动态数组: <syntaxhighlight lang="cpp"> #include <memory> #include <iostream> int main() { auto arr = std::make_unique<int[]>(5); // 创建包含5个int的数组 for (int i = 0; i < 5; ++i) { arr[i] = i * 10; } for (int i = 0; i < 5; ++i) { std::cout << arr[i] << " "; } return 0; } </syntaxhighlight> 输出: <pre> 0 10 20 30 40 </pre> == 与直接使用 new 的对比 == 传统方式使用 <code>new</code> 创建 <code>unique_ptr</code>: <syntaxhighlight lang="cpp"> std::unique_ptr<Point> ptr(new Point(3, 4)); </syntaxhighlight> 使用 <code>make_unique</code> 的改进版本: <syntaxhighlight lang="cpp"> auto ptr = std::make_unique<Point>(3, 4); </syntaxhighlight> 优势对比: 1. 更简洁,不需要重复类型名称 2. 更安全,避免了潜在的异常安全问题 3. 更高效,可能减少内存分配次数 == 异常安全性 == <code>make_unique</code> 提供了更强的异常安全性。考虑以下可能不安全的代码: <syntaxhighlight lang="cpp"> void unsafe_function(int a, int b) { some_function(std::unique_ptr<Point>(new Point(a, b)), std::unique_ptr<Point>(new Point(b, a))); } </syntaxhighlight> 如果其中一个 <code>new</code> 成功而另一个抛出异常,则可能发生内存泄漏。使用 <code>make_unique</code> 可以避免这个问题: <syntaxhighlight lang="cpp"> void safe_function(int a, int b) { some_function(std::make_unique<Point>(a, b), std::make_unique<Point>(b, a)); } </syntaxhighlight> == 实际应用案例 == === 工厂模式 === <code>make_unique</code> 非常适合用于工厂方法: <syntaxhighlight lang="cpp"> #include <memory> #include <iostream> class Shape { public: virtual void draw() = 0; virtual ~Shape() = default; }; class Circle : public Shape { public: void draw() override { std::cout << "Drawing a circle\n"; } }; class Square : public Shape { public: void draw() override { std::cout << "Drawing a square\n"; } }; enum class ShapeType { Circle, Square }; std::unique_ptr<Shape> create_shape(ShapeType type) { switch (type) { case ShapeType::Circle: return std::make_unique<Circle>(); case ShapeType::Square: return std::make_unique<Square>(); } return nullptr; } int main() { auto circle = create_shape(ShapeType::Circle); auto square = create_shape(ShapeType::Square); circle->draw(); square->draw(); return 0; } </syntaxhighlight> 输出: <pre> Drawing a circle Drawing a square </pre> === 资源管理 === <code>make_unique</code> 可以用于管理各种资源: <syntaxhighlight lang="cpp"> #include <memory> #include <fstream> class FileHandler { std::unique_ptr<std::fstream> file; public: FileHandler(const std::string& filename) : file(std::make_unique<std::fstream>(filename)) { if (!file->is_open()) { throw std::runtime_error("Failed to open file"); } } // ... 其他文件操作方法 }; </syntaxhighlight> == 性能考虑 == <code>make_unique</code> 通常比直接使用 <code>new</code> 更高效,因为: 1. 它允许编译器进行更好的优化 2. 它可能减少内存分配的次数(通过合并分配) 3. 它避免了某些类型的重复计算 == 限制 == 1. 不能用于需要自定义删除器的场景 2. 不能直接用于需要共享所有权的情况(此时应使用 <code>make_shared</code>) 3. C++14 之前的标准不支持(但可以自己实现) == 自定义实现(C++11兼容) == 如果你需要使用 C++11,可以自己实现 <code>make_unique</code>: <syntaxhighlight lang="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)...)); } </syntaxhighlight> == 总结 == <code>std::make_unique</code> 是现代 C++ 中创建 <code>unique_ptr</code> 的推荐方式,它提供了: * 更简洁的语法 * 更好的异常安全性 * 更高的代码可读性 * 潜在的性能优势 在大多数情况下,应该优先使用 <code>make_unique</code> 而不是直接使用 <code>new</code> 来创建 <code>unique_ptr</code>。 == 参见 == * [[C++智能指针]] * [[C++ unique_ptr]] * [[C++ make_shared]] [[Category:编程语言]] [[Category:C++]] [[Category:C++ 智能指针]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)