我是一个初学者,我希望我不要因为我不懂术语而重复发表文章,但是我一直在搜寻Stack Overflow和Google,但仍然找不到我的问题的答案,或者至少没有找到答案我能理解。
我正在为单链接列表分配编写Node类。该类有两个字段:elem和next。Elem是模板化的,下一个是Node指针。
我决定编写一个自定义构造函数(以及所有其他构造函数),因此可以确定每个新Node都将next初始化为nullptr,因此不会遇到指针问题。类头:
template <typename E>
class Node {
public:
//Constructors
Node();
Node( const Node<E> &other); //copy
Node<E>& operator=( Node<E> other ); //copy asn
Node( Node&& other ); //move
Node<E>& operator=( Node<E>&& other ); //move asn
~Node();
// {...Getters and setters and the like...}
private:
E elem{}; //datatype independent element
Node<E>* next; //pointer to next list item
};
我的问题是编写move构造函数。据我了解,move构造函数的基本概述如下:
myClass( myClass&& otherMyClassObj ) {
// Step 1: Steal object's resources
myClassField = otherMyClassObj.myClassField;
myClassOtherField = otherMyClassObj.myClassOtherField;
/* ...etc... */
// Step 2: Set other object to a valid but default state so it will be deleted
otherMyClassObj.myClassField = <whatever is default for type>;
otherMyClassObj.myClassOtherField = <whatever is default for type>;
/*...etc...*/
}
但是,当我尝试使用该轮廓在类中编写move构造函数时,我遇到了一个问题:elem的默认状态是什么,我不知道其类型,因为它是在运行时确定的?我的代码为move构造函数:
template <typename E>
Node::Node( Node&& other ) {
next = other.next;
elem = other.elem;
other.next = nullptr;
other.elem = /* ???? */
}
我能想到的唯一解决方案是在另一个上手动调用析构函数,但这似乎草率而错误。我不能使用nullptr,因为elem不一定是指针,但是我不能使用0,因为它可能是一个。我考虑过的另一种可能性是,以某种方式直接在elem上直接调用std :: move(),但是我不确定如何精确地做到这一点,并且在move构造函数中调用move构造函数似乎是天生的错误。
对于这个问题,我将不胜感激。请勿提出非标准的图书馆建议-我很乐意使用它们,但是我的教授对我们使用的图书馆非常严格。
只需移动每个成员。
template <typename E>
Node::Node<E>( Node<E> && other ) : next(std::move(other.next)), elem(std::move(other.elem))
{
}
请注意,我不确定上面确切的模板语法。
遵守5的规则是一件好事,但是如果您不想在某些构造函数,赋值运算符或析构函数中做任何特别的事情,则可以考虑将它们做成= default
。这使事情变得更轻松,更安全。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句