P.S: I am new to programming so please answer my doubts in simpler terms. I have found a couple of answers but could not understand them. Below is the copy constructor and assignment operator overload.
template <class T>
Mystack<T>::Mystack(const Mystack<T> &source) // copy constructor
{
input = new T[source.capacity];
top = source.top;
capacity = source.capacity;
for (int i = 0; i <= source.top; i++)
{
input[i] = source.input[i];
}
}
template <class T>
Mystack<T> & Mystack<T>::operator=(const Mystack<T> &source) // assignment operator overload
{
input = new T[source.capacity];
top = source.top;
capacity = source.capacity;
for (int i = 0; i <= source.top; i++)
{
input[i] = source.input[i];
}
return *this;
}
main function snippet
Mystack <int> intstack = tempstack; (copy constructor)
Mystack <int> floatstack, temp_1;
floatstack = temp_1; (assignment operator)
Understanding : I understand that we need copy and assignment operator so that we can have deep copying in case if we are using heap memory and thus there will be no dangling pointer issue when we delete one of the objects.
Can some one please answer below questions.
1. : Is my understanding correct?
2. : I have been suggested by developers that I have memory leak in assignment operator. If yes, can some please explain me how?
3. Copy constructor has more or less same code as assignment operator then how come I have memory leak only in case of assignment operator but not in the copy constructor function.
4. : In case I really have memory leak. What magic copy and swap idiom does that mem leak gets resolved.
P.S: Its not the complete running code. In actual code objects does contain some data. Kindly bear!