Steve Roy
Steve Roy

Reputation: 13

Move the same unique_ptr into function in a loop

Whats the best way to redesign the following error prone code:

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){
      ..........
}

The goal is to pass the same unique_ptr to function multiple times.

Upvotes: 1

Views: 116

Answers (2)

druckermanly
druckermanly

Reputation: 2741

Pass it by (optionally const) reference to methodB.

So instead of having

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

you can have either of the following

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

or

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

Upvotes: 1

Alan Birtles
Alan Birtles

Reputation: 36409

If you don't want to transfer ownership just pass the raw pointer or a reference. If the functions are going to store the pointer a shared_ptr would be more appropriate:

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

void ClassA::methodB(ClassB::ISomeInterface& obj){
      ..........
}

Upvotes: 2

Related Questions