当以多态方式使用时,派生类的std :: vector成员的复制赋值会导致内存泄漏

Ale*_*lex 0 c++ polymorphism inheritance stdvector

在下面的代码中我想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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

 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
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 10

实际上你的程序调用undefined-behavior.

base类的析构函数必须virtual为了明确定义.

只需将析构函数定义为:

virtual ~base() {}  
Run Code Online (Sandbox Code Playgroud)

即使它是空的,也要这样做!

有关详细信息,请阅读: