C++ 学习(右值引用, std::move)

参考:
http://www.cnblogs.com/lebronjames/p/3614773.html

1.std::move执行一个无条件的转化到右值。它本身并不移动任何东西;

2.std::forward把其参数转换为右值,仅仅在那个参数被绑定到一个右值时;

3.std::move和std::forward在运行时(runtime)都不做任何事。
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <ext/memory>
#include <vector>
#include <set>
#include <string.h>

using namespace std;

class Quote{
  public:
      string ISBN;
      double price;
      Quote() = default;
      Quote(const string &book, const double p):ISBN(book), price(p){};
      virtual   Quote* clone() const & {
         return new Quote(*this);
      }
      virtual Quote* clone()&& {
        return new Quote(std::move(*this));
      }
  public:
      string isbn() const;
      virtual double net_price(size_t n) const{
        return n * price;
      }
};


class Bulk_quote: public Quote{
 private:
      size_t min_qty = 0;
      double discount = 0.9;
      Bulk_quote() = default;
      Bulk_quote(const string &book, double p, size_t qty, double disc):
          Quote(book, p), min_qty(qty), discount(disc){};
 public :
      double net_price(size_t cnt) const {
        if(cnt >= min_qty)
             return cnt*(1-discount)*price;
        else
             return cnt * price;
      }

      Bulk_quote *clone() const &{return new Bulk_quote(*this);};
      Bulk_quote *clone() const &&{return new Bulk_quote(std::move(*this));};
};

double print_total(ostream &os, const Quote &item, size_t n){
   double ret = item.net_price(n);
   os<<"ISBN :"<<item.isbn() << " # sold: "<<n<<" total due:  "<<ret<<endl;
   return ret;
}

class Basket{
  public :
      void add_item(const shared_ptr<Quote> &sale){
         items.insert(sale);
      }
      void add_item(const Quote &sale){
        items.insert(shared_ptr<Quote> (sale.clone()));
      }
      void add_item(const Quote && sale){
      items.insert(shared_ptr<Quote>(std::move(sale).clone()));
      }
      double total_receipt(ostream & os) const{
         double sum = 0.0;
         for(auto iter = items.cbegin(); iter != items.cend(); iter = items.upper_bound(*iter)){
            sum += print_total(os, **iter, items.count(*iter));
         }
         os<<"Total Sale: "<<sum <<endl;
         return sum;
      }
  private:
    static bool compare(const shared_ptr<Quote> &lhs, const shared_ptr<Quote> &rhs){
       return lhs->isbn() < rhs->isbn();
    }
    std::multiset<shared_ptr<Quote>, decltype(compare)*>items;
};


int main()
{

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值