Effective C++: RVO, NRVO.

#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,因为编译器可能存在着对返回类型的优化.

 

转载于:https://my.oschina.net/SHIHUAMarryMe/blog/627827

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值