C++11中std::move和std::forward技术在代理模式与impl模式下混合实例

#ifndef WEIGHT_H
#define WEIGHT_H
#include <memory>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//接口
class IMethed
{
	public:
	virtual void setname(std::string name) = 0;
	virtual void setnumber(double value) = 0;
	virtual double getnumber(int index) = 0;
	virtual int getcount() = 0;
	
};
//接口实现类,含impl技术应用
class Weight : public IMethed
{
public:
    Weight();
	~Weight();
	 Weight(Weight&& rhs);// = default;
    Weight& operator=(Weight&& rhs);// = default;
	void setname(std::string name);
	void setnumber(double value);
	double getnumber(int index);
	int getcount();
private:
    struct Impl;
    std::unique_ptr<Impl> m_impl;
};
//代理类
class Proxy: public IMethed
{
	
	Weight impGG;
	
	public:
	Proxy(Weight&&);
		
	void setname(std::string name);
	
	void setnumber(double value);
	double getnumber(int index);
	int getcount();
	
};

#endif // WEIGHT_H
#include "weightproxy.h"

struct Weight::Impl {
    std::string name;
    vector<double> data;
};

Weight::Weight()
    : m_impl(new Impl())
{

}

Weight::~Weight()
{
	
}

Weight& Weight::operator=(Weight&& rhs)
{
	m_impl = std::move(rhs.m_impl);
	return *this;
}

Weight::Weight(Weight&& rhs)
{
	
	m_impl = std::move(rhs.m_impl);
	
}


void Weight::setname(std::string name)
{
	m_impl->name = name;
}
void Weight::setnumber(double value)
{
	m_impl->data.push_back(value);
}

double Weight::getnumber(int index)
{
	return m_impl->data[index];
}

int Weight::getcount()
{
	return m_impl->data.size();
}




Proxy::Proxy(Weight&& w)
{
	impGG = std::forward<Weight>(w);
}

void Proxy::setname(std::string name)
{
	impGG.setname(name);
}
void Proxy::setnumber(double value)
{
	impGG.setnumber(value);

}

double Proxy::getnumber(int index)
{
	return impGG.getnumber(index);
}

int Proxy::getcount()
{
	return impGG.getcount();
}







int main () {
    Weight w;
    Weight c;
	c.setname("li li");
	c.setnumber(10.0);
	c.setnumber(11.0);
	c.setnumber(12.0);
	c.setnumber(13.0);
	for(int i=0;i<c.getcount();i++)
	cout << "c :"<< c.getnumber(i) <<endl;

    w = std::move(c);
	
	
	for(int i=0;i<w.getcount();i++)
	cout << "w :"<< w.getnumber(i) <<endl;

	
	Proxy p(std::move(w));
	
	
	for(int i=0;i<p.getcount();i++)
	cout << "p :"<< p.getnumber(i) <<endl;

	for(int j=0;j<w.getcount();j++)
		cout << "ww :"<< w.getnumber(j) <<endl;
	
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九江在天

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值