Skip to content

Commit

Permalink
fin shared_ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
archibate committed Dec 13, 2021
1 parent bbb7957 commit 68e8c0b
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 26 deletions.
20 changes: 20 additions & 0 deletions 02/24/0.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <memory>

struct C {
std::shared_ptr<C> m_child;
std::shared_ptr<C> m_parent;
};

int main() {
auto parent = std::make_shared<C>();
auto child = std::make_shared<C>();

// 建立相互引用:
parent->m_child = child;
child->m_parent = parent;

parent = nullptr; // parent 不会被释放!因为 child 还指向他!
child = nullptr; // child 也不会被释放!因为 parent 还指向他!

return 0;
}
20 changes: 20 additions & 0 deletions 02/24/1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <memory>

struct C {
std::shared_ptr<C> m_child;
std::weak_ptr<C> m_parent;
};

int main() {
auto parent = std::make_shared<C>();
auto child = std::make_shared<C>();

// 建立相互引用:
parent->m_child = child;
child->m_parent = parent;

parent = nullptr; // parent 会被释放。因为 child 指向他的是 **弱引用**
child = nullptr; // child 会被释放。因为指向 child 的 parent 已经释放了

return 0;
}
20 changes: 20 additions & 0 deletions 02/24/2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <memory>

struct C {
std::shared_ptr<C> m_child;
C *m_parent;
};

int main() {
auto parent = std::make_shared<C>();
auto child = std::make_shared<C>();

// 建立相互引用:
parent->m_child = child;
child->m_parent = parent.get();

parent = nullptr; // parent 会被释放。因为 child 指向他的是原始指针
child = nullptr; // child 会被释放。因为指向 child 的 parent 已经释放了

return 0;
}
20 changes: 20 additions & 0 deletions 02/24/3.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#include <memory>

struct C {
std::unique_ptr<C> m_child;
C *m_parent;
};

int main() {
auto parent = std::make_unique<C>();
auto child = std::make_unique<C>();

// 建立相互引用:
parent->m_child = std::move(child); // 移交 child 的所属权给 parent
child->m_parent = parent.get();

parent = nullptr; // parent 会被释放。因为 child 指向他的是原始指针
// 此时 child 也已经被释放了,因为 child 完全隶属于 parent

return 0;
}
2 changes: 1 addition & 1 deletion 02/24/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ cmake_minimum_required(VERSION 3.12)
set(CMAKE_CXX_STANDARD 17)
project(hellocpp LANGUAGES CXX)

add_executable(cpptest main.cpp)
add_executable(cpptest 2.cpp)
25 changes: 0 additions & 25 deletions 02/24/main.cpp

This file was deleted.

Binary file modified 02/slides.pptx
Binary file not shown.

0 comments on commit 68e8c0b

Please sign in to comment.