在下面的代码中,我想input
vector<double>
在derived
类中存储一个。我通过应用复制赋值来实现,std::vector
因为向量被传递给setIT
函数。我需要它来使用在派生中实现的计算。在此复制分配期间出现内存泄漏。
可以通过使用来避免这种泄漏:vector<double> * input
而不是vector<double> input
,但我不明白为什么。
任何人都可以澄清这一点吗?提前致谢。
#include "utilities.h"
#include <fstream>
using namespace std;
using namespace astro;
class base
{
public:
base () { cout<<" in base default constructor "<<endl; }
virtual void setIT (void *v) = 0;
virtual double compute () = 0;
};
class derived : public base
{
protected:
vector<double> input;
public:
derived ();
virtual void setIT (void *v);
virtual double compute () { /* using input vector to return something */ return 0; }
};
derived::derived () : base()
{
cout<<" in derived default constructor "<<endl;
input.resize(0);
}
void derived::setIT (void *v)
{
cout<<" in derived setIT "<<endl;
vector<double> * a = reinterpret_cast<vector<double>* >(v);
input = *a;
for (uint i = 0; i<input.size(); i++)
cout<<i<<" "<<input[i]<<endl;
}
int main ()
{
vector<double> test;
fill_linear(test,5,1.,6.); // linear filling of test vector by '5' values between 1 and 6
base * t = new derived;
t->setIT (&test);
cout<<t->compute()<<endl;
delete t;
t = NULL;
return 0;
}
输出:
in base default constructor
in derived default constructor
in derived setIT
0 1
1 2.25
2 3.5
3 4.75
4 6
1