I want to hold a reference to a unique_ptr while using a loop, so that after I get out of the loop I still hold the reference. I know that I can't create a new copy of the unique_ptr (obviously), so what I want to do is something like:
const unique_ptr<Object>& ref;
for(auto& s : stuff) {
if(condition) {
ref = std::move(s);
}
}
I realize this will never work because ref must be initialized at declaration if it is to be a const, but in that same motion I can't hold a reference to a unique_ptr unless it is a const unique_ptr& type if I am not mistaken. What I ended up doing is:
Object* ref = nullptr;
for(auto& s : stuff) {
if(condition) {
ref = s.get();
}
}
Is that a correct solution or should I just consider using shared_ptr for this job?
You shouldn't do any of that! You shouldn't even use a loop [explicitly]! Instead, just find the position and go from there:
auto it = std::find_if(stuff.begin, stuff.end(),
[](std::unique_ptr<Object> const& s){ return condition(s); });
if (it != stuff.end()) {
// get your unique_ptr as appropriate from *it
}
else {
// deal with the fact that nothing was found
}
Functional style to the rescue!
const auto &ref = *std::find_if(stuff.begin(), stuff.end(), [=](const std::unique_ptr<Object> &p) {
return <condition>;
});
Alternatively, move assignment:
std::unique_ptr<Object> ref;
for (auto &&s : stuff) {
if (condition) {
ref = std::move(s);
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With