STU.H
class STU {
public:
STU(string name,int age);
void show();
string _name;
int _age;
};
STU.cpp
STU::STU(string name, int age)
{
_name = name;
_age = age;
}
void STU::show()
{
cout << "名字:" << _name << ";年龄L:" << _age<<endl;
}
main.cpp
// 智能指针.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <memory>
using namespace std;
int main()
{
shared_point();
unique_point();
weak_ponnt();
return 0;
}
// 该对象只能,定义好的指针引用,如果想要其他指针引用必须使用std::move转移指针
void unique_point() {
unique_ptr<STU> ptr(new STU("张三",10));
unique_ptr<STU> ptr2;
STU* test_ptr = new STU("李四", 20);
ptr2 = move(ptr);
ptr2->show();
cout << &ptr2 << endl;
ptr2.reset(test_ptr);
cout << &ptr2 << endl;
test_ptr->show();
ptr2->show();
}
// 有基数功能,对象每次一个指针引用就都计数。
void shared_point() {
shared_ptr<int> ptr(new int(10));
shared_ptr<int> ptr2;
ptr2 = ptr;
ptr2.reset();
cout << ptr << endl;
cout << *ptr << endl;
cout << ptr2 << endl;
ptr.reset();
}
void weak_ponnt() {
shared_ptr<STU> ptr_1 = make_shared<STU>("张三",10);
weak_ptr<STU> wk_ptr= ptr_1;
weak_ptr<STU> wk_ptr2 = ptr_1;
ptr_1->show();
if (ptr_1.unique()) {
cout << "ptr1 is unique!" << endl;
}
cout << "ptr_1 use count : " << ptr_1.use_count() << endl; // 输出:ptr_1 use count : 1
shared_ptr<STU> ptr_2 = make_shared<STU>("李四", 10);
shared_ptr<STU> wk2_ptr = ptr_2;
shared_ptr<STU> wk2_ptr2 = ptr_2;
if (ptr_2.unique()) {
cout << "ptr2 is unique!"<<endl;
}
wk2_ptr2->show();
cout << "ptr_2 use count : " << ptr_2.use_count() << endl; // 输出:ptr_2 use count : 3
}