类成员的C ++内存泄漏 [英] C++ memory leak with class members
问题描述
VS2010中的Debug_VLD揭示了一些由于类成员创建/初始化/删除而引起的内存泄漏.
Debug_VLD in VS2010 reveals some memory leaks that come from class member creation / initialization / deletion.
my_member
是类型为double *的数据成员.在构造函数中,我有
my_member
is a data member with type double*. In constructor, I have
my_member = NULL ;
然后以某种方法,我需要为my_member
分配内存.我不能在构造函数中这样做,
因为我还不知道数组的大小,和/或对于该方法的不同调用大小可能有所不同.我在这种方法中所做的是检查成员是否为NULL.如果是这样,我会为其分配空间,否则,我可以对数组进行操作(使用accesor []更改其元素的值).看起来像
Then in some method, i need to allocate memory for my_member
. I cannot do so in constructor,
since i dont know size of array yet, and/or size may different for different calls of the method. What i do in this method is checking if member is NULL. if so, i allocate space for it, if not, i can operate on array (changing value for its element with accesor []). It looks like
void MyClass::my_method()
{
if( my_member == NULL )
my_member = new double[n_dim] ;
for(int k = 0 ; k < n_dim ; k++ )
my_member[k] = k ;
}
和内存泄漏发生在行my_member = new double[n_dim] ;
.
在析构函数中,我有
delete[] my_member ;
怎么了?如何正确分配?
what is wrong? how to do allocation properly ?
谢谢!
推荐答案
使用std::vector<double>
是首选方法,但是如果您想使用原始的double*
并编写副本构造函数,请手动移动构造函数和operator=
",您应该执行以下操作:
Using std::vector<double>
is the preferred way, but if you want to have raw double*
and write copy constructor, move constructor and operator=
"by hand", you should do something like this:
#include <assert.h> // for assert
#include <algorithm> // for std::swap
class MyClass
{
//
// Raw array
//
double * m_ptr; // raw pointer
size_t m_dim; // number of items in the array
public:
// Default constructor - creates empty vector
MyClass()
: m_ptr(nullptr)
, m_dim(0)
{
}
// Copy constructor
MyClass(const MyClass& src)
: m_ptr(nullptr)
, m_dim(0)
{
// Special case of empty source
if (src.m_dim == 0)
{
assert(src.m_ptr == nullptr);
return;
}
// Allocate and deep-copy from source
m_ptr = new double[src.m_dim];
m_dim = src.m_dim;
for (size_t i = 0; i < m_dim; i++)
m_ptr[i] = src.m_ptr[i];
}
// Move constructor: steal the "guts" from src
MyClass(MyClass&& src)
{
m_ptr = src.m_ptr;
src.m_ptr = nullptr;
m_dim = src.m_dim;
src.m_dim = 0;
}
// Destructor
~MyClass()
{
delete [] m_ptr;
}
// Unified operator=
MyClass& operator=(MyClass src)
{
std::swap(m_ptr, src.m_ptr);
std::swap(m_dim, src.m_dim);
return *this;
}
};
这篇关于类成员的C ++内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!