Why memory leak occurs only in case of overload of the assignment operator, but not in the copy constructor, and how its copy and swap allow

PS: I am new to programming, so please answer my doubts about simpler expressions. I found a couple of answers, but could not understand them. The following is a 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;
}

fragment of the main function

   Mystack <int> intstack = tempstack; (copy constructor)
    Mystack <int> floatstack, temp_1;
    floatstack = temp_1;  (assignment operator)

Understanding: I understand that we need a copy and assignment operator so that we can have deep copy in case we use heap memory, and therefore there will be no problem with a sagging pointer when we delete one of the objects.

Can someone answer below questions.

1 .: Do I understand correctly?

2.: , . , , ?

3. , , , .

4.. , . - .

P.S: . . , !

+4
2

" ?"

, , , . . (copy-ctor, op ) , , , (, , , . ).


" , . , - , ?"

, , :

Mystack<T>::Mystack(size_t size = N)
{
    input = new T[size];
    top = 0;
    capacity = size;
}

- . , :

input = new T[source.capacity]; 

, input ? , . .


" , , , ".

input, copy-ctor. input - ( , ). , .


" , . ".

copy-swap - , "" . , , .

( , ), . :

template <class T>
void Mystack<T>::swap(Mystack<T>& src)
{
    std::swap(input, src.input);
    std::swap(top, src.top);
    std::swap(capacity, src.capacity);
}

:

template <class T>
Mystack<T> & Mystack<T>::operator=(Mystack<T> src) // NOTE by-value intentional,
                                                   // invokes copy-ctor.
{
    this->swap(src);
    return *this;
}

( copy-ctor) . , - , , . , , ( )

, , , (x = x;) . , . x = x;, , , .


. , , , .

+7

, input . , , , .

, , . , , input, . , , , . , :

delete [] input;
+1

Source: https://habr.com/ru/post/1570788/


All Articles