我想创建一个包含迭代器类的列表数据结构。一切正常,但是当我声明移动赋值运算符时,如果程序使用 C++14 或 C++11 标准,则程序无法编译,但在 C++17、C++2a 中运行良好。
列表.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;
};
主.cpp:
#include "list.h"
int main() {
list<int> lst(100);
std::cout << *lst.begin() << std::endl;
}
这是一个精简版,但足以描述问题。
编译器错误和注释消息:
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 {
^~~~~~~~