[英]Why in C++11 or C++14 does the compiler implicitly delete the copy constructor when I declare a move assignment operator?
我想创建一个包含迭代器类的列表数据结构。 一切正常,但是当我声明移动赋值运算符时,如果程序使用 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 {
^~~~~~~~
return iterator(Head);
为什么这在 C++17 中有效是因为在 C++17 中这是保证复制省略。 这里没有复制或移动。
在 return 语句中,当操作数是与函数返回类型相同类类型(忽略 cv 限定)的纯右值时:
在 C++17 之前,这需要一个构造函数,但定义的移动赋值运算符删除了它,在 C++17 中也删除了它,但复制省略不需要它(同上):
复制/移动构造函数不需要存在或可访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.