Holding reference to single_ptr while looping
I want to keep a reference to unique_ptr when using the loop, so that after I exit the loop, I still keep the reference. I know that I cannot create a new copy of 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 understand that this will never work because the ref must be initialized in the declaration if it is supposed to be const, but in the same go, I cannot hold a reference to 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 this the right solution or should I just consider using a shared_ptr for this to work?
source to share
You shouldn't do this! You don't even have to use a loop [explicitly]! Instead, just find the position and 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
}
source to share
Functional style for the rescue!
const auto &ref = *std::find_if(stuff.begin(), stuff.end(), [=](const std::unique_ptr<Object> &p) {
return <condition>;
});
Alternatively, move the assignment:
std::unique_ptr<Object> ref;
for (auto &&s : stuff) {
if (condition) {
ref = std::move(s);
break;
}
}
source to share
I know this may sound contradictory, but given that your object is already managed std::unique_ptr
and therefore guaranteed to be destroyed, I see nothing wrong with using a raw pointer:
Object* o = nullptr;
for(auto& s : stuff) {
if(condition) {
o = s.get();
}
}
if(o) {
// use o->stuff() here
}
source to share