当我们移动一个类类型的时候类型的内部成员并未处于移动状态.
#include <iostream> #include <memory> #include <functional>
template<typename T> class Node{ private: std::unique_ptr<T[]> data; unsigned int counter; public: template<typename Type, typename... Ty> Node(const Type& d, const Ty&... package); Node(const Node<T>& otherNode); Node(Node<T>&& otherNode); Node<T>& operator=(const Node<T>& otherNode); Node<T>& operator=(Node<T>&& otherNode); void print()noexcept; ~Node()=default; };
template<typename T> template<typename Type, typename... Ty> Node<T>::Node(const Type& d, const Ty&... package) :data(nullptr), counter(sizeof...(package)+1) { data.reset(new Type[sizeof...(package)+1]{d, package...}); }
template<typename T> Node<T>::Node(const Node<T>& otherNode) :data(std::unique_ptr<T[]>(new T[otherNode.counter])), //这里其实相当于调用了(this->data).reset(nullptr); counter(otherNode.counter) { std::cout<<"copy-constructor"<<std::endl; std::uninitialized_copy((otherNode.data).get(), (otherNode.data).get()+this->counter, (this->data).get()); }
template<typename T> Node<T>::Node(Node<T>&& otherNode) :data(std::move(otherNode.data)), //注意这里的std::move(). 由于otherNode.data是std::uniuqe_ptr. counter(std::move(otherNode.counter)) //因此移动一个std::unique_ptr相当于: data((otherNode.data).release()); { std::cout<<"move-constructor!"<<std::endl; }
template<typename T> Node<T>& Node<T>::operator=(const Node<T>& otherNode) { std::cout<<"operator=(&)"<<std::endl; if(!otherNode.data){ //判断otherNode.data是不是空. std::allocator<T> a; (this->data).reset(a.allocate(otherNode.counter)); std::uninitialized_copy((otherNode.data).get(), (otherNode.data).get(), (this->data).get()); }else{ std::cout<<"be nullptr"<<std::endl; (this->data).reset(nullptr); } }
template<typename T> Node<T>& Node<T>::operator=(Node<T>&& otherNode) { std::cout<<"operator=(&&)"<<std::endl; if(!otherNode.data){ this->data = std::move(otherNode.data); this->counter = std::move(otherNode.counter); }else{ (this->data).reset(nullptr); } }
template<typename T> void Node<T>::print()noexcept { std::cout<<(this->data)[0]<<std::endl; }
int main() { Node<int> node(5); Node<int> two(2, 89, 0, 1, 4); Node<int> three(2, 3, 4); Node<int> four(three); Node<int> five(std::move(three)); Node<int> six(four); five.print(); return 0; }