智能指针(19)

亡梦爱人 提交于 2019-12-23 02:32:44
#ifndef _A_H_
#define _A_H_
#include <iostream>
using namespace std;

class A {
public:
	int a;
	int b;
	A(int a);
	A(int a, int b);
};

#endif
#include "A.h"

A::A(int a) {
	this->a = a;
	cout << "A::A(int a) a = " << this->a << endl;
}

A::A(int a, int b) {
	this->a = a;
	this->b = b;
	cout << "A::A(int a, int b) a = " << this->a << "  b = " << this->b <<endl;
}
#include "A.h"
#include <memory>

int main() {
	shared_ptr <A> p1 = make_shared<A>(1);
	shared_ptr <A> p2 = make_shared<A>(2, 3);

	cout << "p1->a = " << p1->a << endl;
	cout << "p2->a = " << p2->a << "   p2->b = " << p2->b << endl;

	return 0;
}

//既然这个程序有内存泄漏的风险,而我们平时有有可能忘记delete 那么有什么好办法呢?
//如果指针p有一个析构函数,该析构函数在p过期时候释放它指向的内存,那该多好~
//解决方案:我们引用 "智能指针"
//智能指针: 是行为类似于指针的类对象

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!