【发布时间】:2019-04-21 16:52:40
【问题描述】:
几个月前,我问了this 问题,我问为什么会出现内存泄漏。显然,我忘记了一个虚拟析构函数。
现在我很难理解为什么这不是内存泄漏:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
class Base{
public:
explicit Base(double a){
a_ = a;
}
virtual void fun(){
cout << "Base " << a_ << endl;
}
protected:
double a_;
};
class Derived : public Base{
public:
Derived(double a, double b): Base(a), b_{b}{
}
void fun() override{
cout << "Derived " << a_ << endl;
}
private:
double b_;
};
int main() {
vector<unique_ptr<Base> > m;
for(int i=0; i<10; ++i){
if(i%2 == 0){
m.emplace_back(make_unique<Base>(i));
}else{
m.emplace_back(make_unique<Derived>(i, 2*i));
}
}
for(const auto &any:m){
any->fun();
}
return 0;
}
请注意,我没有Base 的虚拟析构函数。
我认为因为我有一个unique_ptr<Base> 类型的向量m,所以只有来自Base 的析构函数被调用,而我在Derived 中的变量b_ 会泄漏,但根据valgrind,情况并非如此。
为什么这不是内存泄漏?
我已经用 valgrind-3.13.0 对此进行了测试
【问题讨论】:
-
可能有兴趣知道
std::shared_ptr将捕获类型,并调用正确的析构函数。使用std::shared_ptr而不是std::unique_ptr会产生额外的开销。但是,确实应该使用正确的智能指针以捕获意图。使用“错误”的方法来捕获类型,所有这些都是为了避免使析构函数虚拟化,这是一条错误的道路(imo)。
标签: c++ memory-leaks valgrind undefined-behavior unique-ptr