dimanche 30 août 2020

Why in C++11 or C++14 standards compiler implicitly deletes my explicitly declared copy assignment operator when I declare move assignment operator?

I wanted to create list data structure with iterator class in it. Everything works good but when I declare move assignment operator the program doesn't compile if it's C++14 or C++11 standards but works fine in C++17, C++2a.

list.h:

#pragma once

#include <iostream>

template <typename T>
class list {
    struct node {
        node(T data, node* prev = nullptr, node* next = nullptr)
            : data{ data }, prev{ prev }, next{ next } {}
        
        T data;
        node* prev;
        node* next;
    };
public:
    struct iterator {
        template <typename>
        friend class list;

        explicit iterator(node *_node = nullptr) 
            : _node(_node) {}

        iterator& operator=(iterator const &it) {
            _node = it._node;
        
            return *this;
        }
       
        iterator& operator=(iterator &&it) {
            // does nothing
            return *this;
        }

        T& operator*() {
            return _node->data;
        }

    private:
        node *_node;
    };

    list(T data) {
        Head = Tail = new node(data);

        size = 1;
    }

    iterator begin() {
        return iterator(Head);
    }
private:
    node* Head;
    node* Tail;

    int size;
};

main.cpp:

#include "list.h"

int main() {

    list<int> lst(100);

    std::cout << *lst.begin() << std::endl;

}

It's a stripped down version but it's enough to describe the problem.

Compiler error and note message:

error: use of deleted function ‘constexpr list::iterator::iterator(const list::iterator&)’
     return iterator(Head);
                         ^

note: ‘constexpr list::iterator::iterator(const list::iterator&)’ is implicitly declared as
       deleted because ‘list::iterator’ declares a move constructor or move assignment operator
     struct iterator {
        ^~~~~~~~

Aucun commentaire:

Enregistrer un commentaire