#include <iostream>
#include <memory>
#include <vector>
#include <string>
static int flag = 0;
template<typename T>
class Node {
public:
T data{}; //注意这里;
template<typename Ty>
Node(const Ty& key);
Node()=default;
Node(Node<T>&& otherNode_);
Node(const Node<T>& otherNode_);
Node<T>& operator=(const Node<T>& otherNode_);
Node<T>& operator=(Node<T>&& otherNode_);
~Node();
};
template<typename T>
Node<T>::Node(Node<T>&& otherNode_)
: data(std::move(otherNode_.data))
{
std::cout << "move-constructor" << std::endl;
}
template<typename T>
template<typename Ty>
Node<T>::Node(const Ty& key)
:data(key) //注意这里.
{
std::cout << "constructor" << std::endl;
}
template<typename T>
Node<T>::Node(const Node<T>& otherNode_)
{
//copy-constructor.
this->data = otherNode_.data;
}
template<typename T>
Node<T>& Node<T>::operator=(const Node<T>& otherNode_)
{
this->data = otherNode_.data;
return *this;
}
template<typename T>
Node<T>& Node<T>::operator=(Node<T>&& otherNode_)
{
this->data = std::move(otherNode_.data);
return *this;
}
template<typename T>
Node<T>::~Node()
{
std::cout << "destroy: "<< (this->data) << std::endl;
}
Node<std::basic_string<char>> function(Node<std::basic_string<char>> node)
{
std::cout << std::endl;
std::cout << "-------------" << std::endl;
Node<long long int> temp{999999};
std::cout << "--------------" << std::endl;
std::cout << std::endl;
return node;
}
Node<std::basic_string<char>> functionOne(Node<std::basic_string<char>> node)
{
return node;
}
Node<std::basic_string<char>> functionTwo()
{
Node<std::basic_string<char>> temp{ "shihuawoaini" };
return temp;
}
Node<std::basic_string<char>> functionFour()
{
return Node<std::basic_string<char>>{"shihuaMarryMe"};
}
int main()
{
//Node<std::basic_string<char>> theNode{ std::basic_string<char>{"shihua"} };
//function(theNode);
//std::cout << "-----------------" << std::endl;
//1, 首先copy theNode到function的参数node中;
//2, 然后在function中通过默认构造函数构造了temp;
//3, 然后参数node(注意是参数)被 "通过移动构造函数(move-constructor)" 移动到返回值中(需要注意的是返回值其实是一个匿名的临时的右值).
//4, 最后依次执行: temp的析构函数, 参数node的析构函数, 匿名Node的析构函数.
//case 1: NRVO
//functionOne(theNode);
//case 2: NRVO
//functionTwo();
//case 3: RVO
functionFour();
return 0;
}
总结:
绝对不要在函数返回的时候使用std::move和std::forward,因为编译器可能存在着对返回类型的优化.