【问题标题】:Move the same unique_ptr into function in a loop在循环中将相同的 unique_ptr 移动到函数中
【发布时间】:2018-11-10 19:04:27
【问题描述】:

重新设计以下容易出错的代码的最佳方法是什么:

void ClassA::methodA(std::unique_ptr<ClassB::ISomeInterface> obj){
    for (int i = 0; i < 10; i++) {
      methodB(std::move(obj)); // the obj pointer is undefined on second iteration here after the move
    }
  }

void ClassA::methodB(std::unique_ptr<ClassB::ISomeInterface> obj){
      ..........
}

目标是将相同的 unique_ptr 多次传递给函数。

【问题讨论】:

    标签: c++ shared-ptr unique-ptr


    【解决方案1】:

    如果您不想转移所有权,只需传递原始指针或引用。如果函数要存储指针,shared_ptr 会更合适:

    void ClassA::methodA(std::unique_ptr<ClassB::ISomeInterface> obj){
        for (int i = 0; i < 10; i++) {
          methodB(*obj);
        }
      }
    
    void ClassA::methodB(ClassB::ISomeInterface& obj){
          ..........
    }
    

    【讨论】:

      【解决方案2】:

      通过(可选const)引用传递给方法B。

      所以不要有

      void ClassA::methodB(std::unique_ptr<ClassB::ISomeInterface> obj);
      

      你可以有以下任何一种

      void ClassA::methodB(const ClassB::ISomeInterface& obj);
      

      void ClassA::methodB(ClassB::ISomeInterface& obj);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-19
        • 1970-01-01
        • 2017-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多