-
智能指针(存在的问题:循环引用,使用
shared_ptr
和weak_ptr
配合解决); -
QT中的方法,将堆中分配的内存组成森林,然后删除根节点的时候级联删除所有子节点(存在的问题:对异步的支持不友好,因为你不能确定实际调用的时候,指针指向的东东是否还健在,但如果在异步调用的时候,只要保证用到的东西在实际调用前不会被干掉就行)
一个Qt中的例子:
#include <iostream> #include <string> #include <vector> #include <memory> class Object { public: explicit Object(Object* parent = nullptr) { if (parent) { // 如果父类指针不为空(即为树节点),那么将其子类加到vector中 parent->children_.push_back(this); // 这里的this是子类的 } } virtual ~Object() { // 释放所有子类 for (auto& child : children_) { delete child; } } private: std::vector<Object*> children_; }; class Window : public Object { public: explicit Window(const std::string& title, Object* parent = nullptr) : Object(parent), title_(title) {} virtual ~Window() { std::cout << __FUNCTION__ << "\t" << title_ << std::endl; } private: std::string title_; }; class Label : public Object { public: explicit Label(const std::string& text, Object* parent = nullptr) : Object(parent), text_(text) {} ~Label() { std::cout << __FUNCTION__ << "\t" << text_ << std::endl; } private: std::string text_; }; class Button : public Object { public: explicit Button(const std::string& text, Object* parent = nullptr) : Object(parent), text_(text) {} ~Button() { std::cout << __FUNCTION__ << "\t" << text_ << std::endl; } private: std::string text_; }; int main() { { Window* w = new Window("window"); Label* lb = new Label("label", w); Button* btn = new Button("button", w); // 先调用Window的析构函数, 然后再调用Window父类的析构函数(在父类析构函数中delete子类) delete w; } return 0; }
运行结果:
Window::~Window window
Label::~Label label
Button::~Button button