1 Star 0 Fork 2

movetoyushuiqiang / C++11实用新特性

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
unique_ptr共享智能指针的初始化、使用、删除器.cpp 1.88 KB
一键复制 编辑 原始数据 按行查看 历史
#include <iostream>
using namespace std;
#include <string>
#include <functional>
#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()
{
// unique_ptr 是一个独占型的智能指针,他不允许其他的智能指针共享其内部的指针。
//使用构造函数初始化独占智能指针
unique_ptr<int>ptr1(new int(9));
//使用移动构造函数初始化
unique_ptr<int>ptr2 = move(ptr1);
//通过reset初始化
ptr2.reset(new int(8));//放弃的原来的内存空间管理权,重新拥有了另一块空间的管理权
//获取原始指针
unique_ptr<Test>ptr3(new Test(1));
Test* t = ptr3.get();
t->setValue(100);
t->print();
//还有一种方法是直接通过智能指针对象
ptr3->setValue(1000);
ptr3->print();
//删除器
using ptrFunc = void (*)(Test*);
unique_ptr<Test,function<void(Test*)>>ptr4(new Test("hello"), [=](Test* t) {
delete t;
});
//独占的智能指针可以管理数组类型的地址,能够自动释放
unique_ptr < Test[]>ptr5(new Test[3]);
//在C++11中shared_ptr不支持下面写法,C++11以后才支持
shared_ptr < Test[]>ptr6(new Test[3]);
return 0;
}
C++
1
https://gitee.com/jackysq/C--11.git
git@gitee.com:jackysq/C--11.git
jackysq
C--11
C++11实用新特性
master

搜索帮助