簡體   English   中英

將相同的unique_ptr移動到循環中的函數中

[英]Move the same unique_ptr into function in a loop

什么是重新設計以下容易出錯的代碼的最佳方法:

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傳遞給多次。

如果您不想轉移所有權,只需傳遞原始指針或引用即可。 如果函數要存儲指針,則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){
      ..........
}

將它傳遞給(方法為const )對methodB的引用。

所以沒有

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

你可以有以下任何一種

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM