1. shared_ptr 学习
1.1 shared_ptr 定义方法
先定义空指针,再定义指向内容;
std::shared_ptr<int> p1 = std::make_shared<int>();
*p1 = 78;
用在类中:
std::shared_ptr<class> p1 = std::make_shared<class>();
*p1 = new class();
定义指针时新构建类
shared_ptr<class>p1=make_shared<class>(new class());
定义指针来指向旧指针指向的类
shared_ptr<A> pointer2 = pointer;
查看计数
pointer.use_count()
1.2 实验
#include <iostream>
#include <memory>
using namespace std;
class A
{
public:
int A_i = 0;
A() {
cout << "A" <<endl;
}
A(int i) {
A_i = i;
cout << "A" << i << endl;
}
~A() {
cout << A_i<<"~A" << endl;
}
private:
};
void test(shared_ptr<A> &pointer) {
shared_ptr<A> pointer3 = pointer;
cout << "test" << endl;
cout << pointer.use_count() << endl;
cout << "test end" << endl;
}
void test1(shared_ptr<A> pointer) {
shared_ptr<A> pointer3 = pointer;
cout << "test1" << endl;
cout << pointer.use_count() << endl;
cout << "test1 end" << endl;
}
void test2() {
shared_ptr<A> pointer4(new A(4));
cout << pointer4.use_count() << endl;
}
int main()
{
shared_ptr<A> pointer(new A());
cout << pointer.use_count() << endl;
std::shared_ptr<A> pointer2 = pointer;
cout << pointer.use_count() << endl;
test(pointer);
cout << pointer2.use_count() << endl;
test1(pointer);
cout << pointer2.use_count() << endl;
std::shared_ptr<A> pointer5(new A(2));
cout << pointer5.use_count() << endl;
test2();
cout << "test2 end" << endl;
return 0;
}
2 unique_ptr
独占指针;
#include <iostream>
#include <memory>
struct Task {
int mId;
Task(int id) :mId(id) {
std::cout << "Task"<<mId<<"Constructor" << std::endl;
}
~Task() {
std::cout << "Task" << mId << "::Destructor" << std::endl;
}
};
int main()
{
std::unique_ptr<int> ptr1;
if (!ptr1)
std::cout << "ptr1 is empty" << std::endl;
if (ptr1 == nullptr)
std::cout << "ptr1 is empty" << std::endl;
std::unique_ptr<Task> taskPtr(new Task(1));
if (taskPtr != nullptr)
std::cout << "taskPtr is not empty" << std::endl;
std::cout << taskPtr->mId << std::endl;
std::cout << "Reset the taskPtr" << std::endl;
taskPtr.reset();
if (taskPtr == nullptr)
std::cout << "taskPtr is empty" << std::endl;
std::unique_ptr<Task> taskPtr2(new Task(2));
if (taskPtr2 != nullptr)
std::cout << "taskPtr2 is not empty" << std::endl;
{
std::unique_ptr<Task> taskPtr4 = std::move(taskPtr2);
if (taskPtr2 == nullptr)
std::cout << "taskPtr2 is empty" << std::endl;
if (taskPtr4 != nullptr)
std::cout << "taskPtr4 is not empty" << std::endl;
std::cout << taskPtr4->mId << std::endl;
}
std::unique_ptr<Task> taskPtr5(new Task(3));
if (taskPtr5 != nullptr)
std::cout << "taskPtr5 is not empty" << std::endl;
Task * ptr = taskPtr5.release();
if (taskPtr5 == nullptr)
std::cout << "taskPtr5 is empty" << std::endl;
std::cout << ptr->mId << std::endl;
delete ptr;
return 0;
}
3.weak_ptr
std::weak_ptr 用于观察 std::shared_ptr 所指向的对象,通过 weak_ptr 就可以得知对应的 shared_ptr 是否已经被销毁。
weak_prt简介
|