diff --git a/main.cpp b/main.cpp index dc25c6b..8b5c5a1 100644 --- a/main.cpp +++ b/main.cpp @@ -5,29 +5,27 @@ struct Node { // 这两个指针会造成什么问题?请修复 std::shared_ptr next; - std::shared_ptr prev; + std::weak_ptr prev; // 如果能改成 unique_ptr 就更好了! int value; - // 这个构造函数有什么可以改进的? - Node(int val) { - value = val; - } + // 这个构造函数有什么可以改进的? + explicit Node(int val=0): value(val) { } void insert(int val) { auto node = std::make_shared(val); node->next = next; node->prev = prev; - if (prev) - prev->next = node; + if (!prev.expired()) + prev.lock()->next = node; if (next) next->prev = node; } void erase() { - if (prev) - prev->next = next; + if (!prev.expired()) + prev.lock()->next = next; if (next) next->prev = prev; } @@ -43,12 +41,20 @@ struct List { List() = default; List(List const &other) { - printf("List 被拷贝!\n"); - head = other.head; // 这是浅拷贝! + printf("List be copied!\n"); + // head = other.head; // 这是浅拷贝! // 请实现拷贝构造函数为 **深拷贝** + head = std::make_shared(other.head->value); + auto now = head, othead = other.head; //浅拷贝 + while(othead->next){ + now->next = std::make_shared(othead->next->value); + now->next->prev = now; + now = now->next, othead = othead->next; + } } - List &operator=(List const &) = delete; // 为什么删除拷贝赋值函数也不出错? + List &operator=(List const &) = delete; + // 为什么删除拷贝赋值函数也不出错? 因为编译器默认使用析构函数+拷贝构造来代替拷贝赋值函数 List(List &&) = default; List &operator=(List &&) = default; @@ -80,7 +86,7 @@ struct List { } }; -void print(List lst) { // 有什么值得改进的? +void print(const List& lst) { // 有什么值得改进的?传参const List&,减少拷贝并提高运行速度,减少运行时内存占用 printf("["); for (auto curr = lst.front(); curr; curr = curr->next.get()) { printf(" %d", curr->value);