我正在使用Valgrind检查内存泄漏。
不幸的是,我收到4
警告。
附加的是我的代码的简化版本,它再现了错误:
Leak_DefinitelyLost
丢失发生在#include <iostream>
#include <vector>
#include <memory>
#include <unordered_map>
using namespace std;
class Base{
public:
explicit Base(double a){
a_ = a;
}
virtual void fun() = 0;
protected:
double a_;
};
class Derived_A : public Base{
public:
Derived_A(double a, vector<double> b, vector<double> c): Base(a), b_{b}, c_{c}{
}
void fun() override{
cout << "Derived_A " << a_ << endl;
}
private:
vector<double> b_;
vector<double> c_;
};
class Derived_B : public Base{
public:
Derived_B(double a, double b, double c): Base(a), b_{b}, c_{c}{
}
void fun() override{
cout << "Derived_B " << a_ << endl;
}
private:
double b_;
double c_;
};
int main() {
unordered_map<string, unique_ptr<Base> > m;
for(int i=0; i<10; ++i){
unique_ptr<Base> o;
if(i%2 == 0){
vector<double> b{1., 2., 3.};
vector<double> c{4., 5., 6.};
o = make_unique<Derived_A>(i, move(b), move(c));
m[to_string(i)] = move(o);
}else{
double b = 1.;
double c = 2.;
o = make_unique<Derived_B>(i, b, c);
m[to_string(i)] = move(o);
}
}
for(const auto &any:m){
any.second->fun();
}
return 0;
}
通话期间:
make_unique
我不确定自己在做什么错。有人可以澄清错误发生的地方吗?
(我从CLion 2018.1.5,Valgrind 3.13.0中呼叫Valgrind。)