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 回答