在实际的 C++ 开发中,我们经常会遇到诸如程序运行中突然崩溃、程序运行所用内存越来越多最终不得不重启等问题,这些问题往往都是内存资源管理不当造成的。比如:
#include
#include
using namespace std;
int main()
{
std::unique_ptr<int> p5(new int);
*p5 = 10;
// p 接收 p5 释放的堆内存
int * p = p5.release();
cout << *p << endl;
//判断 p5 是否为空指针
if (p5) {
cout << "p5 is not nullptr" << endl;
}
else {
cout << "p5 is nullptr" << endl;
}
std::unique_ptr<int> p6;
//p6 获取 p 的所有权
p6.reset(p);
cout << *p6 << endl;;
return 0;
}
输出:
10
p5 is nullptr
10
std::shared_ptr p4 = new int(1) //mistake 创建shared_ptr的方式:
/*
* @Author: Phoenix_Z
* @Date: 2022-09-02 17:22:45
* @Last Modified by: Phoenix_Z
* @Last Modified time: 2022-09-02 17:22:45
* @Description:
*/
#include
#include
using namespace std;
class Student
{
public:
char *m_name;
Student(char *name) : m_name(name){};
~Student()
{
cout << "im:" << m_name << "," << "destroied" << endl;
}
};
int main()
{
char * name = "james";
shared_ptr<Student> p1 = make_shared<Student>(name); //创建shared_ptr
shared_ptr<Student> p2(p1);
shared_ptr<Student> p3 = p2;
Student *p = p3.get(); //将智能指针(类)指向的地址传递给指针
cout << p->m_name << "," //指向同一块堆区,所以析构函数此时只调用一次
<< p1->m_name << ", "
<< p2->m_name << ", "
<< p3->m_name << "\n"
<< "p3 count:" << p3.use_count() << ", " //use_count()计数
<< endl;
p1.reset(new Student("kobe")); //此时p1改变了指向的地址
cout << p1->m_name << endl;
cout << "p1 after changed:" <<p1.use_count() << endl;
cout << "p3 count after p1 changed:: " << p3.use_count() << endl;
p2.reset();
cout << "p3 count after p2 changed:" <<p3.use_count() << endl;
return 0;
}
/*
运行结果:
james,james, james, james
p3 count:3,
kobe
p1 after changed:1
p3 count after p1 changed:: 2
p3 count after p2 changed:1
im:james,destroied
im:kobe,destroied
*/
#include
#include
using namespace std;
int main()
{
std::shared_ptr<int> sp1(new int(10));
std::shared_ptr<int> sp2(sp1);
std::weak_ptr<int> wp(sp2);
//输出和 wp 同指向的 shared_ptr 类型指针的数量
cout << wp.use_count() << endl;
//释放 sp2
sp2.reset();
cout << wp.use_count() << endl;
//借助 lock() 函数,返回一个和 wp 同指向的 shared_ptr 类型指针,获取其存储的数据
cout << *(wp.lock()) << endl;
return 0;
}
输出:
2
1
10