2020.11.23 第13课 C++智能指针
01_auto_ptr与unique_ptr
--------------------------------
智能指针 4个模板类
1.auto_ptr C++11放弃
2.unique_ptr
3.shared_ptr
4.weak_ptr
--------------------------------
#include <iostream>
#include <string>
using namespace std;
class MM
{
public:
MM(string name):name(name){
}
MM(string* name):name(*name){
}
~MM()
{
cout << "MM的析构过程" << endl;
}
friend ostream& operator<<(ostream& out, MM object)
{
out << object.name << endl;
return out;
}
protected:
string name;
};
void print()
{
MM* pMM = new MM("LBW");
if (1)
return;
delete pMM;
}
int main()
{
auto_ptr<MM> p1(new MM("LBW"));
auto_ptr<MM> p2;
p2 = p1;
cout << *p2 << endl;
unique_ptr<string> p3(new string("要求更严格智能指针"));
unique_ptr<string> p4;
p4 = move(p3);
cout << "p4:" << *p4 << endl;
cout << "p3:" << *p3 << endl;
unique_ptr<string>* p5 = new unique_ptr<string>(new string("new一个智能指针"));
MM* pM = new MM(new string("pMM"));
delete p5;
return 0;
}
02_shared_ptr