L
LiDongning
Hi,
I'm working on a class which allocate some memory to store an array
(pointed by a pointer p_data). In constructor I use new to do the
allocation, in destructer I use delete to free the memory. In one
member function I wan to do something with the data (say, sort). In
that case, inside that function, I plan to allocate a piece memory to
store the processed data (p_processed), then free the original memory
(p_data), and point the p_data to p_process. The code will be
something like attached below. My question is, can i do something like
in the last two lines of code? Will this cause a memory leak or any
harmful effect? Thanks very much!
template <class T>
class data
{
int datanum;
T* p_data;
public:
data(int, T*);
~data();
void process();
};
template <class T>
data<T>::data(int in_n, T* in_data):datanum(in_n)
{
T* p_data = new T[datanum];
for (int i=0; i<datanum; i++) {p_data=in_data;}
}
template <class T>
data<T>::~data()
{
delete []p_data;
}
template <class T>
void data<T>:
rocess()
{
T* p_processed= new T[datanum];
//do something, so p_processed will be filled with processed data
for (int i=1; i<datanum; i++) {p_processed=p_data;}
//processing finished
delete []p_data; // can i
do this??
p_data = p_processed; // can i do
this??
}
I'm working on a class which allocate some memory to store an array
(pointed by a pointer p_data). In constructor I use new to do the
allocation, in destructer I use delete to free the memory. In one
member function I wan to do something with the data (say, sort). In
that case, inside that function, I plan to allocate a piece memory to
store the processed data (p_processed), then free the original memory
(p_data), and point the p_data to p_process. The code will be
something like attached below. My question is, can i do something like
in the last two lines of code? Will this cause a memory leak or any
harmful effect? Thanks very much!
template <class T>
class data
{
int datanum;
T* p_data;
public:
data(int, T*);
~data();
void process();
};
template <class T>
data<T>::data(int in_n, T* in_data):datanum(in_n)
{
T* p_data = new T[datanum];
for (int i=0; i<datanum; i++) {p_data=in_data;}
}
template <class T>
data<T>::~data()
{
delete []p_data;
}
template <class T>
void data<T>:
{
T* p_processed= new T[datanum];
//do something, so p_processed will be filled with processed data
for (int i=1; i<datanum; i++) {p_processed=p_data;}
//processing finished
delete []p_data; // can i
do this??
p_data = p_processed; // can i do
this??
}