Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Hủy ảo dùng shared_ptr trong C++

Để xóa đúng đối tượng lớp dẫn xuất qua con trỏ lớp cơ sở, định nghĩa hủy hàm (destructor) của lớp cơ sở là virtual. Sử dụng shared_ptr quản lý bộ nhớ tự động.

Ví dụ

#include <iostream>
#include <memory>
using namespace std;

class Base {
public:
    Base() { cout << "Constructing Base" << endl; }
    virtual ~Base() { cout << "Destructing Base" << endl; }
};

class Derived : public Base {
public:
    Derived() { cout << "Constructing Derived" << endl; }
    ~Derived() { cout << "Destructing Derived" << endl; }
};

int main() {
    shared_ptr<Base> sp{ new Derived };
    return 0;
}

Đầu ra

Constructing Base
Constructing Derived
Destructing Derived
Destructing Base