代码拉取完成,页面将自动刷新
同步操作将从 夜空中最亮的星/C++11实用新特性 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
#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;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。