在映射值中从 unique_ptr 迭代原始指针

Iterate raw pointers from unique_ptr in map values

我在地图值中使用 unique_ptr。我需要将这些值作为原始指针的 list/vector 获取。到目前为止,我已经做了如下。

#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <map>

class Foo {
  public:
    std::string val;

    Foo(std::string v) : val(v) {
    }
 };

 class Unique {
   public:
     std::map<int, std::unique_ptr<Foo>> unique_map;

     std::vector<Foo*> getFoos() {
       std::vector<Foo*> foos;
       for (auto& it : unique_map) {
         foos.push_back(it.second.get());
       }

       return foos;
     }
 };

 int main() {
   Unique unique;
   Foo* f1 = new Foo("1");
   Foo* f2 = new Foo("2");

   unique.unique_map.emplace(1, f1);
   unique.unique_map.emplace(2, f2);

   std::vector<Foo*> foos = unique.getFoos();

   for (Foo* foo : foos) {
     std::cout << foo->val;
   }

   std::cout<<"\n";

   return 0;
 }

但是编译失败。最相关的错误消息似乎是

"/usr/include/c++/4.8/bits/stl_tree.h:140:49: note: cannot convert ‘std::forward((* & __args#1))’ (type ‘Foo*’) to type ‘const std::unique_ptr&’"

但我不确定我是否理解它的含义,因为我的理解是 it.second returns 对 unique_ptr 的引用不是Foo 实例它自己假设这就是问题所在。需要做什么来修正这个例子?

编辑 我使用的是较旧的 g++ 版本。

g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4

使用命令行。

g++ -std=c++11 -o unique unique.cpp

当我运行这段代码时,投诉似乎与std::pairclass的创建有关。

unique.unique_map.emplace(1, std::unique_ptr<Foo>(f1));
unique.unique_map.emplace(2, std::unique_ptr<Foo>(f2));

对我来说,这个构建并且有效,但我不能肯定地说它真的会做你想要的。只是它为我编译和运行s。

我的大部分 C++ 时间都在使用 QT 库和 classes,但是,在我看来,它似乎无法找到一种方法将带有 FOO* 的一对转换为unique_ptr<FOO>

您收到的错误是因为不允许将 Foo* 隐式转换为 std::unique_ptr<Foo>。这是因为,unique_ptr 的构造函数采用原始指针标记为 explicit.

explicit
      unique_ptr(pointer __p) noexcept
      : _M_t(__p, deleter_type())
      { static_assert(!is_pointer<deleter_type>::value,
                     "constructed with null function pointer deleter"); }

因此,您应该在执行 emplace

的同时创建 unique_ptrmove

注意:我不确定为什么或如何在 g++ > 6.0 库中工作。但我个人认为将原始指针隐式转换为智能指针并不安全。要了解原因,请参阅: