Reputation: 13
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
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
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