赞
踩
std::unique_ptr提供了一种安全、自动化的方式来管理动态分配的内存,并且在对象不再需要时自动释放内存。
创建对象数组,要求类必须具有缺省构造函数,实现不提供参数也能构造对象的能力。
- #include <iostream>
-
- class Person
- {
- public:
- int m_age = 10;
-
- Person(int age = 1) : m_age(age)
- {
- std::cout << "New... age = " << m_age << "\n";
- }
-
- ~Person()
- {
- std::cout << "Delete... age = " << m_age << "\n";
- }
-
- void Disp() const
- {
- std::cout << "age = " << m_age << "\n";
- }
- };
- void fun1(std::unique_ptr<Person>& ptr)
- {//参数为指向单个对象的智能指针
- ptr->Disp();
- }
- void fun2(int n, std::unique_ptr<Person[]>& ptr)
- {//参数为指向对象数组的智能指针
- for (int i = 0; i < n; ++i)
- {
- ptr[i].Disp();
- }
- }
-
-
- int main()
- {
- std::unique_ptr<Person> pPeron1 = std::make_unique<Person>(20);// 创建一个Person,参数为20
- fun1(pPeron1);
- std::unique_ptr<Person> pPeron2(new Person(30));// 创建一个Person,参数为30
- fun1(pPeron2);
-
- int n = 3;
- std::unique_ptr<Person[]> arr(new Person[n]); // 利用缺省构造函数,创建一个包含3个Person的动态数组
- fun2(n, arr);
-
- std::unique_ptr<Person[]> arr2=std::make_unique<Person[]>(n); // 利用缺省构造函数,创建一个包含3个Person的动态数组
- fun2(n, arr2);
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。