以多态方式使用派生类的std::vector成员的复制赋值会导致内存泄漏
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
的复制赋值来实现这一点,因为将向量传递给setIT
函数。我需要使用compute,它是在派生中实现的。在此副本分配过程中出现内存泄漏。
这个泄漏可以通过使用: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
实际上你的程序调用了未定义行为。
base
类的析构函数必须为virtual
才能定义良好。
只需定义析构函数为:
virtual ~base() {}
即使为空也要执行此操作!
详情请参阅:
- 什么时候我的析构函数应该是虚的?
避免在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*/;}
};
相关文章:
- 复制构造函数、赋值运算符C++
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 为用户定义的类正确调用复制构造函数/赋值运算符
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- C++矢量复制构造函数和赋值运算符是否也复制保留空间?
- 了解构造函数在移动、复制、赋值语义中的行为
- 如何在双向链表上实现复制赋值?
- 使用赋值运算符复制 std::vector
- 复制赋值函数如何访问另一个对象的私有成员(Stroustroup 原则和实践书)?
- 为什么基类中的复制和交换会导致派生类中的复制赋值运算符被隐式删除?
- 复制构造函数和赋值运算符的值类实现
- 在C++中,我可以在定义自己的复制构造函数后跳过定义赋值运算符吗?
- 复制和赋值构造函数的问题
- 为什么我的类工作正常,即使在返回垃圾值作为赋值运算符和空复制构造函数的返回之后
- 在c++中重载复制赋值运算符
- 按值从函数返回对象并在赋值/复制 C'tor C++ 中使用它
- 赋值复制构造函数
- 成员初始化列表vs赋值/复制构造函数(在boost deadline_timer中)
- 类使用自身/深度复制时赋值/复制操作符重载