的容器unique_ptr
似乎没有什么意义:你不能将它与初始化列表一起使用,而且我无法遍历容器(下面的解决方法)。我是不是误会了什么?或者什么时候使用unique_ptr
STL 容器才有意义?
#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;
}
以下问题帮助我找到了这些解决方法: