polymorph.cpp里面的“析构函数、智能指针”问题

源代码:

cpp 复制代码
#include <iostream>
// /*
struct Base 
{
    virtual void f(){}
};
struct Derived:Base 
{
    void f() override {}
};
int main()
{
    Base *p = new Derived;
    return 0;
}
// */

/*
#include <memory>

struct Base 
{
    virtual void f() {}
    //virtual ~Base() = default;
};

struct Derived : Base 
{
    void f() override {}
};

int main()
{
    std::unique_ptr<Base> p = std::make_unique<Derived>();
    p->f();
    std::cout << "  Derived class object is created and function f() is called." << std::endl;
}

*/

分析 polymorph.cpp 中的问题与修复建议

文件分析

文件中包含了两段代码,都被注释掉了第一段。逐一分析:

第一段代码(第 2-15 行,被 /* */ 注释)

cpp 复制代码
struct Base
{
    virtual void f(){}
};
struct Derived:Base
{
    void f() override {}
};
int main()
{ 
    Base *p = new Derived;
    return 0;
}

存在的问题:

  1. 内存泄漏 :使用 new Derived 创建了对象,但从未调用 delete 来释放内存。
  2. 缺少析构函数:基类没有虚析构函数,在多态使用时可能导致资源泄漏。

第二段代码(第 18-39 行,被 /* */ 注释)

cpp 复制代码
struct Base
{
    virtual void f() {}
    //virtual ~Base() = default;
};
struct Derived : Base
{
    void f() override {}
};
int main()
{
    std::unique_ptr<Base> p = std::make_unique<Derived>();
    p->f();
    std::cout << "  Derived class object is created and function f() is called." << std::endl;
}

这段代码是正确的:

  1. 使用了智能指针 std::unique_ptr 避免泄漏。
  2. 虚函数正常工作。
  3. 如果取消注释第 24 行的虚析构函数会更好。

建议的修复方案

方案一:手动管理内存(添加虚析构函数 + delete)

cpp 复制代码
#include <iostream>

struct Base
{
    virtual void f(){}
    virtual ~Base() = default;  // 添加虚析构函数
};

struct Derived : Base
{
    void f() override {}
};

int main()
{
    Base *p = new Derived;
    delete p;  // 释放内存
    return 0;
}

方案二:使用智能指针(推荐)

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

struct Base
{
    virtual void f(){}
    virtual ~Base() = default;
};

struct Derived : Base
{
    void f() override {}
};

int main()
{
    std::unique_ptr<Base> p = std::make_unique<Derived>();
    return 0;
}

总结

主要问题就是内存管理 和虚析构函数缺失 。在涉及多态的场景中,基类应始终提供虚析构函数,并优先使用智能指针来避免手动 new/delete 带来的泄漏风险。

相关推荐
神一样的老师7 小时前
WS63 BLE 配网实战:用 Python 在 PC 上替代手机完成 WiFi 配网
开发语言·python·智能手机
geovindu8 小时前
python: Decision Tree
开发语言·后端·python·决策树
时间的情敌9 小时前
Three.js 工业场景性能优化合集|大批量管线、InstancedMesh 实例化、合并 Geometry、显存释放
开发语言·javascript·性能优化·three.js
步峰代理-盾山10 小时前
R语言爬虫实战:使用httr与XML解析网页数据并进行统计分析
xml·开发语言·爬虫·r语言·网络爬虫
sharemylove20 小时前
Java集合框架全面详解
java·开发语言·经验分享·笔记·学习
郝学胜-神的一滴1 天前
Effective Python 条款43:自定义容器类
开发语言·windows·python·pandas·scikit-learn·pyqt
好焊孙辉1 天前
一条产线省下 30 个电机位:Z 轴和 R 轴,该合成一个了
开发语言·r语言
布莱克6051 天前
Swift 中的逃逸闭包与非逃逸闭包:@escaping 到底在做什么
开发语言·ios·swift·闭包·逃逸
郝学胜-神的一滴1 天前
Effective STL 条款 14:用扩容函数避免重新分配
linux·开发语言·网络·数据结构·c++·单片机
旖旎夜光1 天前
LeetCode 493: 翻转对 (归并排序) —— 题解
c++·笔记·学习·算法·leetcode·排序算法