Re: Destructors And Operator Overloading
On 10 Apr., 10:41, =D7=A8=D7=9E=D7=99 <Ste...@gmail.com> wrote:
[..]
The implementation of the operator is:
myClass<T> myClass<T>::operator+(const myClass<T>& cls)
{
int i;
myClass<T> res(cls.size);
for (i=0;i<cls.size;i++)
{
res.data[i] = data[i];
}
return res;
}
[..]
The problem is, that after the last line of the operator+ - "return
res"
I don't know why, but the destructor is called for "res",
Which means that the object returned, is already cleaned!!!
What am I missing\doing wrong?
Your implementation creates a local variable res that is destroyed
when leaving the function body, hence the destructor call.
"return res" provides a copy of res to the caller.
However, in the member "data", a copy of the pointer is provided that
is used to store your array in local variable. When your destructor
frees the memory, the pointer in the returned object becomes invalid.
You have two options:
1. provide a copy constructor that does a "deep copy". I.e. allocates
a new buffer and copies the memory content pointed to.
2. avoid T*, use a std::vector<T> instead. This will do all memory
allocation issues transparently for you, no need for memory
deallocation in a destructor, no need to write a copy constructor
yourself.
The solution 2. is what I would prefer. Your adapted class may look
like this:
template <class T>
class myClass {
private:
std::vector<T> data;
/* int size; */ // obsolete, use data.size() if you have to.
public:
myClass( int s );
myClass<T> operator+( const myClass<T>& vec );
/* ~myClass(); */ // obsolete, default destructor handles data
member
};
If "data" is *the* central member of your class, to make handling more
convenient I'd also consider inheritance:
template <class T>
class myClass : private std::vector<T> {
...
};
The implementation of your + operator will become:
template <class T>
myClass<T>::operator + ( const myClass<T>& cls ) {
return *this = cls; // that's probably not what you intended?
}
best,
Michael.