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的析构函数中,它会调用正确的析构函数,这就是智能指针的强大之处。

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

相关推荐
xiangyun6111 小时前
【408数据结构 08】队列:循环队列判空判满,408年年考,一次讲清
c语言·开发语言·数据结构·c++·算法
xiangyun6112 小时前
【408数据结构 06】双链表、循环链表、静态链表
c语言·开发语言·数据结构·c++·算法
OKkankan13 小时前
LangChain 能力详解!:输出解析、RAG、向量数据库与 Retriever 检索器
数据结构·python·langchain·ai应用
蓝速科技13 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发
xxwxx__13 小时前
C++ AVL 树深度剖析:平衡二叉搜索树原理、源码与面试考点
数据结构·c++
Logic10114 小时前
C语言/数据结构数组题解:数字列表加一(Plus One)——进位处理与数组扩展
c语言·数据结构·模拟·数组·时间复杂度·算法题·进位
xxwxx__17 小时前
C++ STL set 与 map 全套详解:关联式容器、红黑树底层、代码坑点、刷题实战
数据结构·c++
程曦曦18 小时前
MySQL 生产库误删 98 张表后的时间点恢复实战:从 binlog 解析到资金对账
linux·数据结构·其他·算法·ubuntu·运维开发
郝学胜-神的一滴18 小时前
Effective Python 条款 13:善用星号解包,告别下标切片拆分的坑
服务器·开发语言·数据结构·python·程序人生·pycharm
Logic10118 小时前
C语言/数据结构位运算题解:异或XOR找出流水线上的“独特零件编号“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质