代码之家  ›  专栏  ›  技术社区  ›  Finley

关于在成员重载中使用std::move()的问题

  •  1
  • Finley  · 技术社区  · 6 年前

    ,最后一个话题 模拟虚拟拷贝 在第15章。

    定义两个按继承相关的分类:

    class Quote{
    public:
    virtual Quote* clone() const & {return new Quote(*this);}
    virtual Quote* clone() && {return new Quote(std::move(*this));}
    //other members
    };
    
    class Bulk_quote: public Quote{
    public:
    Bulk_quote* clone() const& {return new Bulk_quote(*this);}
    Bulk_quote* clone() && {return new Bulk_quote(std::move(*this));}
    //other members
        };
    

    class {
    public:
      void add_item(const Quote& sale)   //copy the given object
        { items.insert(std::shared_ptr<Quote>(sale.clone()));}
      void add_item(Quote&& sale)  //move the given object
        {items.insert(std::shared_ptr<Quote>(std::move(sale).clone()));}
    //other memebers
    private:
      static bool compare(const std::shared_ptr<Quote>& lhs,const std::shared_ptr<Quote>& rhs)
    {return lhs->isbn() < rhs->isbn();}
    std::multiset<std::shared_ptr<Quote>,decltype(compare)*> items(compare);
    };
    

    我陷入了两个观察中:

    std::move(*this) 在成员定义中 virtual Quote* clone()&& ? 据我所知,这个版本只能在reference限定符下的一个可修改的rvalue(比如,临时对象)上运行 && 标准::移动(*此) 替换为 *this ?

    (2) 类似于(1),为什么 std::move(sale) 在成员的第二个定义中 add_item 只能在rvalue的对象上运行。仅供参考 Quote&& sale 只能绑定到右值,是吗 有必要吗?

    添加\u项 书中说“尽管sale类型是一个右值引用类型,sale(和其他变量一样)是一个左值”。然而,verison void add_item(const Quote& sale) sale 是左值。谁能帮我?

    1 回复  |  直到 6 年前
        1
  •  0
  •   xskxzr    6 年前

    你好像把物体和表情搞混了。值类别(lvalue或rvalue)是表达式的属性,而不是对象的属性,因此即使, *this 作为表达式 仍然是左值。我也是 sale .

    • 形式的表达 *expr

    • 作为表达式的变量的非限定名称始终是左值。