循环时保持对unique_ptr的引用

Bla*_*cal 3 c++ gcc c++11

我想在使用循环时保持对unique_ptr的引用,这样在我离开循环后我仍然保持引用.我知道我不能创建unique_ptr的新副本(显然),所以我想做的是:

const unique_ptr<Object>& ref;
for(auto& s : stuff) {
    if(condition) {
         ref = std::move(s);
    }
}
Run Code Online (Sandbox Code Playgroud)

我意识到这将永远不会起作用,因为ref必须在声明时初始化,如果它是一个const,但在同一个动作中我不能保持对unique_ptr的引用,除非它是一个const unique_ptr&type如果我没有弄错的话.我最终做的是:

Object* ref = nullptr;
for(auto& s : stuff) {
    if(condition) {
         ref = s.get();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个正确的解决方案还是我应该考虑使用shared_ptr来完成这项工作?

The*_*ant 6

功能风格的救援!

const auto &ref = *std::find_if(stuff.begin(), stuff.end(), [=](const std::unique_ptr<Object> &p) {
    return <condition>;
});
Run Code Online (Sandbox Code Playgroud)

或者,移动分配:

std::unique_ptr<Object> ref;
for (auto &&s : stuff) {
    if (condition) {
        ref = std::move(s);
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)


Die*_*ühl 6

你不应该这样做!你甚至不应该使用循环[明确]!相反,只需找到位置并从那里开始:

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
}
Run Code Online (Sandbox Code Playgroud)