c++ - 循环时持有对 unique_ptr 的引用

标签 c++ c++11 gcc

我想在使用循环时保留对 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/

相关文章:

c++ - 这段代码不应该崩溃吗

c++ - 两个 libstdc++.so.6 文件和版本 `GLIBCXX_3.4.21' 未找到错误

c++ - 在知道变量是什么数据类型之前如何声明变量?

c++ - 如果我只使用指向基类的指针,更改私有(private)派生类是否会影响 ABI?

c++ - vector 对统一初始化

gcc - 如何将D-Bus交叉编译到ARM?

c - 如何在编译时在 gcc 中显示 #define 的值

c++ - 转发引用不是被推导出为 r 值引用吗?

c++ - 如何静态断言模板枚举类型? (C++11)

c++ - gcc 选项 "-fmessage-length"是什么意思?