为什么赋值运算符即使在被禁止的情况下也能工作?
Why assignment operator working even when it was forbidden?
我又在与 OOP 作斗争了。我尝试实现单向链表,代码如下:
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;
}
}
};
我不假思索地写了一些行,即arr = list()
和*this = list()
。我没有实现 operator=
所以应该会有一些麻烦。我以为编译器已经决定为我生成 copy/move 分配,所以我决定添加这些行,只是出于好奇:
list& operator=(const list& arr) = delete;
list& operator=(list&& arr) = delete;
但它仍然编译,我不明白为什么。这是怎么回事?不应该禁止赋值,因此 arr = list()
和 *this = list()
是非法的吗?
不评估模板 unless/until 您实例化它们。如果您不使用复制或移动构造函数,则它们的错误不会产生错误。
我又在与 OOP 作斗争了。我尝试实现单向链表,代码如下:
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;
}
}
};
我不假思索地写了一些行,即arr = list()
和*this = list()
。我没有实现 operator=
所以应该会有一些麻烦。我以为编译器已经决定为我生成 copy/move 分配,所以我决定添加这些行,只是出于好奇:
list& operator=(const list& arr) = delete;
list& operator=(list&& arr) = delete;
但它仍然编译,我不明白为什么。这是怎么回事?不应该禁止赋值,因此 arr = list()
和 *this = list()
是非法的吗?
不评估模板 unless/until 您实例化它们。如果您不使用复制或移动构造函数,则它们的错误不会产生错误。