1 Star 0 Fork 2

movetoyushuiqiang / C++11实用新特性

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
shared_ptr共享智能指针的初始化、使用、删除器.cpp 3.27 KB
一键复制 编辑 原始数据 按行查看 历史
#include <iostream>
using namespace std;
#include <string>
#include <memory>//智能指针的头文件
//智能指针是存储指向动态分配(堆)对象指针的类,用于生存期的控制,能够确保在离开所在的作用域时,自动地销毁动态分配的对象,防止内存泄漏。
//智能指针的核心实现技术是引用计数,每使用一次,内部引用计数加一,每析构一次内部的引用计数减一,减为零时,删除所指向的堆内存。
//C++11中提供了三种智能指针,使用这些智能指针都需要包含头文件 <memory>
//shared_ptr:共享指针指针
//unique_ptr:独占的智能指针
//weak_ptr:弱引用的智能指针,它不共享指针,不能操作资源,是用来监视 shared_ptr 的
class Test
{
public:
Test()
{
cout << "construst Test ..." << endl;
}
Test(int x) :m_num(x)
{
cout << "construst Test, x = " << x << endl;
}
Test(string str)
{
cout << "construst Test, str = " << str << endl;
}
~Test()
{
cout << "destrust Test..." << endl;
}
void setValue(int v)
{
m_num = v;
}
void print()
{
cout <<"m_num: " << m_num << endl;
}
private:
int m_num;
};
int main()
{
//shared_ptr共享智能指针的四种初始化方式
//通过构造函数初始化
shared_ptr<int> ptr1(new int(3));
cout << "ptr1 use_count: " << ptr1.use_count() << endl;
//通过移动构造和拷贝构造函数初始化
shared_ptr<int> ptr2 = move(ptr1);//移动构造函数初始化
cout << "ptr1 use_count: " << ptr1.use_count() << endl;
cout << "ptr2 use_count: " << ptr2.use_count() << endl;
shared_ptr<int> ptr3 = ptr2;//拷贝构造函数初始化
cout << "ptr2 use_count: " << ptr2.use_count() << endl;
cout << "ptr3 use_count: " << ptr3.use_count() << endl;
//通过std::make_shared 初始化
shared_ptr<int> ptr4 = make_shared<int>(8);
shared_ptr<Test> ptr5 = make_shared<Test>(8);//调用int类型的构造函数
shared_ptr<Test> ptr6 = make_shared<Test>("hello world");//调用string类型的构造函数
//通过reset初始化
ptr6.reset();//之前的 ptr6 引用计数为1 现在为0 这块内存就被析构了
cout << "ptr6 use_count: " << ptr6.use_count() << endl;
ptr5.reset(new Test("tom"));//ptr5之前管理的内存空间释放了,现在管理的是新开辟的空间new Test("tom") 注意:新开辟的内存空间类型必须要和ptr5维护的类型一致
cout << "ptr5 use_count: " << ptr5.use_count() << endl;
//输出结果:
/* ptr1 use_count : 1
ptr1 use_count : 0
ptr2 use_count : 1
ptr2 use_count : 2
ptr3 use_count : 2
construst Test, x = 8
construst Test, str = hello world
destrust Test...
ptr6 use_count : 0
construst Test, str = tom
destrust Test...
ptr5 use_count : 1
destrust Test...*/
//共享智能指针 shared_ptr 的使用
//获取原始指针
Test* t = ptr5.get();
t->setValue(1000);
t->print();
//通过智能指针对象直接操作
ptr5->setValue(999);
ptr5->print();
//指定删除器 当 shared_ptr 指针释放管理内存的时候,会调用自带的删除器。我们也可以自己指定删除器函数
shared_ptr<Test> p(new Test(100), [](Test* t) {
//释放内存操作
cout << "-------------------------------------------------" << endl;
delete t;
});
//什么时候需要指定删除器呢? 当智能指针对象管理一个数组,需要指定一个删除器
//shared_ptr<Test> ppp(new Test[5]);//自带的删除器是不能删除数组类型的地址
shared_ptr<Test> pp(new Test[5], [](Test* t) {
delete[] t;
});
//除了自己编写删除器,还可以使用C++提供的std::default_delete<T>()函数为删除器
shared_ptr<Test> ppp(new Test[3], default_delete<Test[]>());
return 0;
}
C++
1
https://gitee.com/jackysq/C--11.git
git@gitee.com:jackysq/C--11.git
jackysq
C--11
C++11实用新特性
master

搜索帮助