我想在使用循环时保留对 unique_ptr 的引用,这样在我退出循环后我仍然保留引用。我知道我无法创建 unique_ptr 的新拷贝(显然),所以我想做的是:
const unique_ptr<Object>& ref;
for(auto& s : stuff) {
if(condition) {
ref = std::move(s);
}
}
我意识到这永远行不通,因为 ref 必须在声明时初始化,如果它是一个 const,但在同样的 Action 中,我不能持有对 unique_ptr 的引用,除非它是一个 const unique_ptr& 类型,如果我不是错误。 我最终做的是:
Object* ref = nullptr;
for(auto& s : stuff) {
if(condition) {
ref = s.get();
}
}
这是一个正确的解决方案还是我应该考虑使用 shared_ptr 来完成这项工作?
最佳答案
你不应该这样做!你甚至不应该[明确地]使用循环!相反,只需找到位置并从那里开始:
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
}
关于c++ - 循环时持有对 unique_ptr 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27653421/