当前位置:   article > 正文

利用智能指针std::unique_ptr创建单个对象和对象数组_智能指针创建数组

智能指针创建数组

std::unique_ptr提供了一种安全、自动化的方式来管理动态分配的内存,并且在对象不再需要时自动释放内存。

创建对象数组,要求类必须具有缺省构造函数,实现不提供参数也能构造对象的能力。

  1. #include <iostream>
  2. class Person
  3. {
  4. public:
  5. int m_age = 10;
  6. Person(int age = 1) : m_age(age)
  7. {
  8. std::cout << "New... age = " << m_age << "\n";
  9. }
  10. ~Person()
  11. {
  12. std::cout << "Delete... age = " << m_age << "\n";
  13. }
  14. void Disp() const
  15. {
  16. std::cout << "age = " << m_age << "\n";
  17. }
  18. };
  1. void fun1(std::unique_ptr<Person>& ptr)
  2. {//参数为指向单个对象的智能指针
  3. ptr->Disp();
  4. }
  5. void fun2(int n, std::unique_ptr<Person[]>& ptr)
  6. {//参数为指向对象数组的智能指针
  7. for (int i = 0; i < n; ++i)
  8. {
  9. ptr[i].Disp();
  10. }
  11. }
  12. int main()
  13. {
  14. std::unique_ptr<Person> pPeron1 = std::make_unique<Person>(20);// 创建一个Person,参数为20
  15. fun1(pPeron1);
  16. std::unique_ptr<Person> pPeron2(new Person(30));// 创建一个Person,参数为30
  17. fun1(pPeron2);
  18. int n = 3;
  19. std::unique_ptr<Person[]> arr(new Person[n]); // 利用缺省构造函数,创建一个包含3个Person的动态数组
  20. fun2(n, arr);
  21. std::unique_ptr<Person[]> arr2=std::make_unique<Person[]>(n); // 利用缺省构造函数,创建一个包含3个Person的动态数组
  22. fun2(n, arr2);
  23. return 0;
  24. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/781589
推荐阅读
相关标签
  

闽ICP备14008679号