Disclaimer; I realize some users are against "using namespace std;" and I don't use it in my actual code, I just thought it was more clear for the example.
Most of the code is pretty straight forward. I have a vector<Base> that can hold a list of pointers to derived classes to avoid slicing. One of those derived classes actually holds a vector<Base> itself. The problem comes when I try to push this class (called "DerivedArray" in the code below) into another vector<Base>.
if I comment out the "derived_items" member code I can push_back without problems.
#include <stdio.h>
#include <vector>
#include <iostream>
#include <memory>
usingnamespace std;
class Base {};
class Derived : public Base {};
class DerivedArray : public Base {
public:
DerivedArray(vector<unique_ptr<Base>>& vector) {
derived_items = move(vector);
};
private:
vector<unique_ptr<Base>> derived_items;
};
int main()
{
Derived d1;
vector<unique_ptr<Base>> items;
items.push_back(make_unique<Derived>(d1));
DerivedArray da{items};
// re-use items, which is now empty after the elements have been moved in DerivedArray's constructor
items.push_back(make_unique<DerivedArray>(da)); // error
return 0;
}
I have a hunch that there is somewhere a copy going on inside "make_unique()" that violates the uniqueness of the "unique_ptr"'s stored "derived_items", but I can't reason why because the function name suggests I get a unique reference to my DerivedArray "da".
Note that I'm not very proficient in plowing through the big list of errors of the template functions.
Unique_ptrs do not have a copy constructor. They cannot be copied, only moved. Think about it, if a unique_ptr could be copied (which means a single resource can have more than one pointer pointing to it), that wouldn't make the unique_ptr very "unique", would it?