智能指针的定义:能自动管理内存
#include<iostream>
#include<memory>
#include<string>
using namespace std;
class Student
{
public:
Student(string name,int age):name(name),age(age){}
Student() {
cout << "构造函数的调用" << endl;
}
~Student()
{
cout << "析构函数调用" << endl;
}
void print()
{
cout << "学生姓名:" << this->name << "年龄:" << this->age << endl;
}
private:
string name;
int age;
};
void closefile(FILE * p)
{
cout << "文件关闭成功" << endl;
fclose(p);
}
void print(shared_ptr<Student> S)
{
S->print();
}
auto returnptr()
{
shared_ptr<Student> p = make_shared<Student>("chengliu", 46);
return p;
}
int main()
{
//1.智能指针的对象
//No.1无参构造
shared_ptr<int> p;
if (!p)
{
cout << "智能指针为空" << endl;
}
//No.2new方式
shared_ptr<int> data(new int(42));
//No.3makeshare函数
shared_ptr<string> str = make_shared<string>("I LOVE C++");
{
//构造自定义数据类型的共享指针"张三", 18由构造函数的参数决定
shared_ptr<Student> str = make_shared<Student>("张三", 18);
}
//2.智能指针的成员
/*
get()函数:返回一个内置指针,指向管理对象,不能delete这个指针
use_count():返回与p共享对象的智能指针的数量
swap():交换对象
reset():重置对象
*/
shared_ptr<Student> S1 = make_shared<Student>("李四", 19);
cout << S1.use_count() << endl;//结果为1
//两个函数作用相同
S1->print();
S1.get()->print();
auto S2(S1);
cout << S1.use_count() << endl;//结果为2
S2.reset();
cout << S1.use_count() << endl;//结果为1
cout << S2.use_count() << endl;//结果为0
S2.reset(new Student("王五",20));
cout << S2.use_count() << endl;//结果为1
//3.智能指针的几个使用场景
//No.1作为函数参数传入
print(S2);
//No.2作为函数返回值
auto S3 = returnptr();
print(S3);
//4.如果你使用智能指针管理的资源不是new分配的内存,记住传递给它一个删除器
{
cout << "正常用法:" << endl;
shared_ptr<Student> p(new Student[10], [](Student* S) {delete[]S; });
}
//读写文件相关
{
shared_ptr<FILE> p(fopen("1.txt", "w+"), closefile);
}
}
在此程序中运行遇到了点问题,报错报错'fopen': this function or variable may be unsafe. consider using fopen_s instead. to disable deprecation, use _crt_secure_no_warnings. see online h
解决办法:#define _CRT_SECURE_NO_WARNINGS加在程序文件最上边,必须是最上边