Re: Destructors And Operator Overloading
On Apr 10, 12:48 pm, Michael.Boehni...@gmail.com wrote:
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 da=
ta
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 intend=
ed?
}
best,
Michael.- Hide quoted text -
- Show quoted text -
Ok, so I understand that if I'll add a:
myClass(const myClass<T>& cls);
it will work.
But what if I overloaded the operator= as well (for other reasons),
Than if I perform this line:
cls3 = cls1 + cls2
What will happen is that 2 instances will be created:
One from "cls1 + cls2" - by the new copy constructor,
And another from the "cls3 = result" by the operator=
How can I minimize that?
Thanks all
--sternr