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?
Aucun commentaire:
Enregistrer un commentaire