0

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
4

2 に答える 2

10

実際、あなたのプログラムは未定義の動作を呼び出します。

baseクラスのデストラクタは、明確に定義するために必要です。virtual

デストラクタを次のように定義するだけです。

virtual ~base() {}  

空いていてもやりましょう!

詳細については、これを読んでください。

于 2013-03-05T14:35:35.087 に答える
0

C++ で void ポインターを使用しないでください。異なるタイプを処理したい場合は、代わりにテンプレートを使用してください。

class Base
{
public:
  virtual ~Base(){}
  virtual double compute() const=0;
};

template<typename T>
class Derived : public Base
{
private:
  std::vector<T> m_input;
public:
  void set_it(const T& in)
  {
    m_input = in;
  }
  double compute() const{/*Do the computation and return*/;}
};
于 2013-03-05T14:48:15.943 に答える