Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why assignment operator working even when it was forbidden?

I’m struggling with OOP again. I tried to implement signgly linked list, here’s the code:

template <typename T>
class node
{
    T value;
    node* next;

public:
    node(const T& n)
    {
        this->value = n;
        this->next = nullptr;
    }
    ~node()
    {
        //is it ok to leave destructor empty in my case?
    }
};

template <typename T>
class list
{
    node<T>* head;
    node<T>* tail;

public:
    list()
    {
        this->head = nullptr;
        this->tail = nullptr;
    }
    list(const list& arr)
    {
        *this = list(); //<================== the line I mentioned
        node* current_this = this->head;
        node* current_arr = this->arr;
        while (current_arr != nullptr)
        {
            current_this = new node(current_arr);
            current_arr = current_arr->next;
            current_this = current_this->next;
        }
    }
    list(list&& arr)
    {
        this->head = arr.head;
        this->tail = arr.tail;
        arr = list(); //<================== the line I mentioned
    }
    ~list()
    {
        node* current = this->head;
        while (current != nullptr)
        {
            node* next = current->next;
            delete current;
            current = next;
        }
    }
};

I wrote some lines without thinking, i.e. arr = list() and *this = list(). I didn’t implemented operator= so there should be some troubles. I thought compiler has decided to generate copy/move assigment for me, so I decided to add these lines, just for curiosity sake:

list& operator=(const list& arr) = delete;
list& operator=(list&& arr) = delete;

But it still compiled and I don’t understand why. What’s the deal here? Shoudn’t assignment be forbidden and therefore arr = list() and *this = list() be illegal?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Templates aren’t evaluated unless/until you instantiate them. If you don’t use the copy or move constructor, then their bugs don’t produce errors.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading