c++ 智能指针的使用
2024-08-27 03:05:46
https://www.cnblogs.com/TenosDoIt/p/3456704.html
#include <QCoreApplication>
#include <string>
#include <iostream>
#include <memory> using namespace std; class Test
{
public:
Test(string s)
{
str = s;
cout<<"Test creat : " << str << endl;
}
~Test()
{
cout<<"Test delete:"<<str<<endl;
}
string& getStr()
{
return str;
}
void setStr(string s)
{
str = s;
}
void print()
{
cout<<str<<endl;
}
private:
string str;
}; unique_ptr<Test> fun()
{
return unique_ptr<Test>(new Test(""));
} int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv); auto_ptr<Test> ptest0(new Test(""));
ptest0->setStr("hello ");
ptest0->print();
ptest0.get()->print();
ptest0->getStr() += "world !";
(*ptest0).print();
ptest0.reset(new Test(""));
ptest0->print();
cout << "\n"; unique_ptr<Test> ptest1(new Test(""));
unique_ptr<Test> ptest2(new Test(""));
ptest1->print();
ptest2 = std::move(ptest1);//不能直接ptest2 = ptest1
if(ptest1 == NULL)cout<<"ptest = NULL\n";
Test* p = ptest2.release();
p->print();
ptest1.reset(p);
ptest1->print();
ptest2 = fun(); //这里可以用=,因为使用了移动构造函数
ptest2->print();
cout << "\n"; shared_ptr<Test> ptest(new Test(""));
shared_ptr<Test> ptest23(new Test(""));
cout<<ptest23->getStr()<<endl;
cout<<ptest23.use_count()<<endl;
ptest = ptest23;//"456"引用次数加1,“123”销毁
ptest->print();
cout<<ptest23.use_count()<<endl;//
cout<<ptest.use_count()<<endl;//
ptest.reset();
ptest23.reset();//此时“456”销毁
cout<<"done !\n"; return a.exec();
}
最新文章
- MVC实用构架设计(三)——EF-Code First(6):数据更新最佳实践
- [不好分类]SD卡无法读取,显示RAW
- 移动端字体缩放问题解决方案-摘自《html5移动web开发实践》
- [转]响应式WEB设计学习(2)—视频能够做成响应式吗
- android 开发小记
- java jps命令
- 自动化测试LoadRunner
- xml转array
- GCD使用经验与技巧浅谈--备
- 无法Debug SQL: Unable to start T-SQL Debugging. Could not attach to SQL Server process on
- 关路灯,洛谷dp
- 简单认识python cmd模块
- Dede 删除文档同时文章中的图片的方法
- 潭州课堂25班:Ph201805201 第四课:Linux的命令以及VIM的使用 (课堂笔记)
- Jmeter远程测试
- linux下开启某个端口的方法:可用于SQL
- 代码整洁之道Clean Code 读后感After Reading
- FastDFS分布文件系统Java客户端使用
- vue中的img src 动态加载本地json的图片路径写法。
- eclipse+cdt+cygwin做C++