A container of unique_ptr
seems to make little sense: you cannot use it with initializer lists and I failed to iterate through the container (workarounds below). Am I misunderstanding something? Or when does it make sense to use unique_ptr
and STL containers?
#include <memory>
#include <vector>
using namespace std;
struct Base { void go() { } virtual ~Base() { } };
// virtual ~Base() = default; gives
// "declared virtual cannot be defaulted in the class body" why?
class Derived : public Base { };
int main() {
//vector<unique_ptr<Base>> v1 = { new Derived, new Derived, new Derived };
//vector<shared_ptr<Base>> v2 = { new Derived, new Derived, new Derived };
vector<Base*> v3 = { new Derived, new Derived, new Derived };
vector<shared_ptr<Base>> v4(v3.begin(), v3.end());
vector<unique_ptr<Base>> v5(v3.begin(), v3.end());
for (auto i : v5) { // works with v4
i->go();
}
return 0;
}
The following questions helped me find these workarounds: