When does it make sense to use unique_ptr with STL containers? (C ++ 11)

The container unique_ptrseems unlikely: you cannot use it with initializer lists, and I was unable to iterate through the container (workarounds below). I do not understand something? Or when does it make sense to use containers unique_ptrand 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;
}

<The following questions helped me find these workarounds:

+5
source share
3 answers
for (auto i : v5) {
  i->go();
}

Must be

for (auto& i : v5) { // note 'auto&'
  i->go();
}

.

, , std::unique_ptr std::shared_ptr explicit. - :

#include <iterator> // make_move_iterator, begin, end

template<class T>
std::unique_ptr<T> make_unique(){ // naive implementation
  return std::unique_ptr<T>(new T());
}

std::unique_ptr<Base> v1_init_arr[] = {
    make_unique<Derived>(), make_unique<Derived>(), make_unique<Derived>()
};

// these two are only for clarity
auto first = std::make_move_iterator(std::begin(v1_init_arr));
auto last = std::make_move_iterator(std::end(v1_init_arr));
std::vector<std::unique_ptr<Base>> v1(first, last);

std::vector<std::shared_ptr<Base>> v2 = {
    std::make_shared<Derived>(),
    std::make_shared<Derived>(),
    std::make_shared<Derived>()
};

Good Thing β„’, ( , ). unique_ptr, , unique_ptr , .


, std::map<std::string, std::unique_ptr<LoaderBase>> .

+14

unique_ptr STL, , . .

,

vector<Base*> v3 = { new Derived, new Derived, new Derived };

, v3 .

+1

std::unique_ptr<T>... ( ) . - vector<unique_ptr<Base>>::iterator vector<unique_ptr<Base>>::const_iterator.

+1
source

All Articles