Подтвердить что ты не робот

Итерация через вектор <unique_ptr <mytype>> с использованием С++ 11 для() циклов

У меня есть следующая серия кода:

std::vector<std::unique_ptr<AVLTree_GeeksforGeeks>> AVLArray(100000);

/* Let add some objects in the vector */
AVLTree_GeeksforGeeks *avl = new AVLTree_GeeksforGeeks();
avl->Insert[2]; avl->Insert[5]; AVL->Insert[0];
unique_ptr<AVLTree_GeeksforGeeks> unique_p(avl);
AVLArray[0] = move(unique_p);
/* we do this for a number of other trees, let say another 9...
...
...
Now the vector has objects up until AVLTree[9] */

/* Let try iterating through its valid, filled positions */
for(auto i : AVLTree )
{
   cout << "Hey there!\n";    //This loop should print 10 "Hey there"s.
}

Ruh roh. Ошибка компиляции в последней части в цикле for().

\DataStructures2013_2014\main.cpp||In function 'int main()':|
\DataStructures2013_2014\main.cpp|158|error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = AVLTree_GeeksforGeeks; _Dp = std::default_delete<AVLTree_GeeksforGeeks>; std::unique_ptr<_Tp, _Dp> = std::unique_ptr<AVLTree_GeeksforGeeks>]'|
e:\codeblocks\mingw\bin\..\lib\gcc\mingw32\4.7.1\include\c++\bits\unique_ptr.h|256|error: declared here|
||=== Build finished: 2 errors, 0 warnings (0 minutes, 0 seconds) ===|

Любые идеи о том, что я делаю неправильно?

4b9b3361

Ответ 1

Цикл

for (auto i: AVLTree) { ... }

пытается сделать копию каждого элемента диапазона в AVLTree.begin() и AVLTree.end(). Конечно, std::unique_ptr<T> нельзя скопировать: для каждого указателя есть только один std::unique_ptr<T>. На самом деле он ничего не копировал, а украл бы. Это было бы плохо.

Вместо этого вы хотите использовать ссылки:

for (auto& i: AVLTree) { ... }

... или, если вы не изменяете их

for (auto const& i: AVLTree) { ... }