源代码:
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;
}
存在的问题:
- 内存泄漏 :使用
new Derived创建了对象,但从未调用delete来释放内存。 - 缺少析构函数:基类没有虚析构函数,在多态使用时可能导致资源泄漏。
第二段代码(第 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;
}
这段代码是正确的:
- 使用了智能指针
std::unique_ptr避免泄漏。 - 虚函数正常工作。
- 如果取消注释第 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 带来的泄漏风险。