使用链表在堆栈中考虑这个完全正常工作的复制和交换习惯用法.
//first is the pointer to the recently added node
//n is the size of the stack
template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
Stack<T> copy{s};
std::swap(copy.n,n);
std::swap(copy.first,first);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
根据这个,std :: swap"交换给定的值." 所以我想为什么不交换两个堆栈的整个值,为什么只是它的项目?
template<class T>
Stack<T>& Stack<T>::operator=(Stack&& s) {
Stack<T> copy{s};
std::swap(copy, *this);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
为什么不定义?
小智 6
你引入了无限递归.赋值运算符是std::swap在引擎盖下使用的构造之一,因此你operator=将调用swap哪个将调用operator=哪个将调用swap哪个将调用operator=哪个将调用swap哪个将调用operator=哪个将调用swap哪个将调用operator=哪个将调用swap哪个将调用operator=哪个将调用swap哪个调用operator=分段错误