[英]copy assignment of std::vector member of a derived class causes memory leak when used in a polymorphic way
在下面的代碼中,我想在derived
類中存儲input
vector<double>
。 我是通過將std::vector
的副本分配應用於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
實際上,您的程序會調用undefined-behavior。
base
類的析構函數必須是virtual
,以便定義明確。
只需將析構函數定義為:
virtual ~base() {}
即使它是空的,也要這樣做!
有關詳細信息,請閱讀以下內容:
避免在C ++中使用空指針。 如果要處理其他類型,請改用模板。
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*/;}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.