I am using unique_ptr in map values. I need to get those values as a list/vector of raw pointers. So far I have done as follows.
#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;
}
But this fails to compile. The most relevent error message seems to be
"/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&’"
But I am not sure I understand what it means since my understanding is that it.second returns a reference to the unique_ptr not the Foo instance it self assuming that's where the problem is. What needs to be done to fix this example?
Edit I am using a somewhat older g++ version.
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
with command line.
g++ -std=c++11 -o unique unique.cpp