Bootstrap

C++ shared_ptr

为了解决内存泄漏问题,C++标准库内包含了智能指针,shared_ptr是其中的一种。

#include<iostream>
#include<memory>
using namespace std;

int main()
{
	int *pa = new int(1);
	shared_ptr<int> sp = make_shared<int>(*pa);
	shared_ptr<int> sp1 = sp;
	cout << pa << endl;
	cout << *sp << " " << *sp1 << endl;
	cout << sp << " " << sp1 << endl;
	cout << sp.get() << " " << sp1.get() << endl;
	cout << sp.use_count() << " " << sp1.use_count() << endl;
	
	cout << endl;
	*pa = 4;
	cout << *sp << " " << *sp1 << endl;
	cout << sp << " " << sp1 << endl;
	cout << sp.get() << " " << sp1.get() << endl;
	cout << sp.use_count() << " " << sp1.use_count() << endl;

	cout << endl;
	*sp = 4;//改变原始指针没用
	cout << *sp << " " << *sp1 << endl;
	cout << sp << " " << sp1 << endl;
	cout << sp.get() << " " << sp1.get() << endl;
	cout << sp.use_count() << " " << sp1.use_count() << endl;

	cout << endl;
	*sp1 = 8;
	cout << *sp << " " << *sp1 << endl;
	cout << sp << " " << sp1 << endl;
	cout << sp.get() << " " << sp1.get() << endl;
	cout << sp.use_count() << " " << sp1.use_count() << endl;

	cout << endl;
	int* p = sp.get();
	*p = 9;
	cout << *sp << " " << *sp1 << endl;
	cout << sp << " " << sp1 << endl;
	cout << sp.get() << " " << sp1.get() << endl;
	cout << sp.use_count() << " " << sp1.use_count() << endl;
	
	cout << endl;
	{
		shared_ptr<int> sp2 = sp1;//作用于完了后就会销毁
		cout << sp.use_count() << " " << sp1.use_count() << " " << sp2.use_count() << endl;
	}
	cout << sp.use_count() << " " << sp1.use_count() << endl;

	system("pause");
	return 0;

}

在这里插入图片描述
总结:
传入智能指针的只是值,而不是引用,因此会生成新的变量,导致原始指针pa与sp.get()得到的指针指向的空间不是同一处,因此改变原指针pa指向的内容不会改变智能指针指向的内容。***(为甚么会这样,存在疑问????)***

悦读

道可道,非常道;名可名,非常名。 无名,天地之始,有名,万物之母。 故常无欲,以观其妙,常有欲,以观其徼。 此两者,同出而异名,同谓之玄,玄之又玄,众妙之门。

;