为了解决内存泄漏问题,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指向的内容不会改变智能指针指向的内容。***(为甚么会这样,存在疑问????)***