boost::ref

在C++的算法和函数之间,以类对象作为参数的情况很非常常见的问题,一般情况下传值语义是可行的,但也有很多特殊情况,作为参数的函数对象拷贝代价过高(具有复杂的内部状态),或者不希望拷贝对象(内部状态不应该被改变),甚至拷贝是不可行的(noncopyable、单件)。

boost.ref应用代理模式,引入对象引用的包装器概念解决这个问题。它位于名字空间boost,为了使用ref组件,需要包含头文件<boost/ref.hpp>,即

#include<boost/ref.hpp>

using namespace boost;

示例代码为:

  1. #include <boost/assign.hpp>
  2. #include <boost/ref.hpp>
  3. #include <boost/typeof/typeof.hpp>//BOOST_AUTO宏
  4. using namespace boost;
  5. using namespace boost::assign;
  6. //该函数是用来测试typedef void result_type的功能,但此处好像并未使用到它
  7. void TestRef1()
  8. {
  9. struct square
  10. {
  11. typedef void result_type;//验证改行的意义
  12. void operator()(int &x)
  13. {
  14. x = x * x;
  15. }
  16. };
  17. vector<int> v = (list_of(1),2,3,4,5);
  18. for_each(v.begin(), v.end(), square());
  19. copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
  20. cout<<endl;
  21. }
  22. class big_class
  23. {
  24. private:
  25. int x;
  26. public:
  27. big_class():x(0){}
  28. void print()
  29. {
  30. cout<<"big_class "<<++x<<endl;
  31. }
  32. };
  33. template<typename T>
  34. void print(T a)
  35. {
  36. for (int i = 0;i < 2;++i)
  37. {
  38. unwrap_ref(a).print();//解包装
  39. }
  40. }
  41. void main()
  42. {
  43. big_class c;
  44. BOOST_AUTO(rw,ref(c));
  45. c.print();//输出1
  46. print(c);//拷贝传参,输出2,3,内部状态不变
  47. print(rw);//引用传参,输出2,3, 内部状态改变
  48. print(c);//拷贝传参,输出4,5,内部状态不变
  49. c.print();//输出4
  50. }
#include <boost/assign.hpp>
#include <boost/ref.hpp>
#include <boost/typeof/typeof.hpp>//BOOST_AUTO宏
using namespace boost;
using namespace boost::assign;

//该函数是用来测试typedef void result_type的功能,但此处好像并未使用到它
void TestRef1()
{
	struct square 
	{
		typedef void result_type;//验证改行的意义
		void operator()(int &x)
		{
			x = x * x;
		}
	};

	vector<int> v = (list_of(1),2,3,4,5);
	for_each(v.begin(), v.end(), square());

	copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
	cout<<endl;
}

class big_class
{
private:
	int x;
public:
	big_class():x(0){}
	void print()
	{
		cout<<"big_class "<<++x<<endl;
	}
};


template<typename T>
void print(T a)
{
	for (int i = 0;i < 2;++i)
	{
		unwrap_ref(a).print();//解包装
	}
}

void main()
{
	big_class c;
	BOOST_AUTO(rw,ref(c));
	c.print();//输出1

	print(c);//拷贝传参,输出2,3,内部状态不变
	print(rw);//引用传参,输出2,3, 内部状态改变
	print(c);//拷贝传参,输出4,5,内部状态不变
	c.print();//输出4
}


运行结果:

big_class 1
big_class 2
big_class 3
big_class 2
big_class 3
big_class 4
big_class 5
big_class 4
请按任意键继续. . .

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值