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