std::shared_ptr 和多态的组合使用//test ok

在 C++ 中,std::shared_ptr 和多态(通过虚函数和基类指针/引用实现)可以很好地结合使用。这种组合通常用于管理对象的生命周期,同时允许通过基类指针或引用来实现多态。

下面是一个简单的示例,演示如何使用 std::shared_ptr 来管理多态对象的生命周期:

cpp 复制代码
#include <iostream>
#include <memory>

// 基类
class Shape {
public:
    virtual void draw() const {
        std::cout << "Drawing a shape" << std::endl;
    }

    virtual ~Shape() {
        std::cout << "Destroying a shape" << std::endl;
    }
};

// 派生类
class Circle : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a circle" << std::endl;
    }

    ~Circle() override {
        std::cout << "Destroying a circle" << std::endl;
    }
};

class Square : public Shape {
public:
    void draw() const override {
        std::cout << "Drawing a square" << std::endl;
    }

    ~Square() override {
        std::cout << "Destroying a square" << std::endl;
    }
};

int main() {
    // 使用 std::shared_ptr 管理多态对象的生命周期
    std::shared_ptr<Shape> shapePtr = std::make_shared<Circle>();
    shapePtr->draw();  // 调用派生类的虚函数

    // 另一个派生类
    shapePtr = std::make_shared<Square>();
    shapePtr->draw();  // 同样调用派生类的虚函数

    // 在 main 函数结束时,std::shared_ptr 会自动销毁对象,调用相应的析构函数
    return 0;
}
/*
root@PF34VVBR:/mnt/c/Users/User/Documents/test# g++ sharedptr_duotai.cpp -o sharedptr_duotai.o
root@PF34VVBR:/mnt/c/Users/User/Documents/test# ./sharedptr_duotai.o
Drawing a circle
Destroying a circle
Destroying a shape
Drawing a square
Destroying a square
Destroying a shape
*/

在这个例子中,Shape 是一个基类,CircleSquare 是派生类。通过使用 std::shared_ptr<Shape>,我们可以在运行时指向 CircleSquare 对象,而不用担心手动释放内存。在std::shared_ptr的析构函数中,它会调用正确的析构函数,这就是智能指针的强大之处。

这种方法还可以用于容器等数据结构,让你在使用多态的同时,充分发挥智能指针的便利性。

相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚2 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap