1

I'm working on my little project about pointers, I ran into problem when I was trying to push a unique_ptr to a derived class, to a vector of unique_ptr to base class. It keeps saying that I'm "attempting to reference to a deleted function". I tried to use push_back with and without std::move but nothing worked...

#include<iostream>
#include<memory>
#include<vector>

using namespace std;

class Base {};
class Derived : public Base {};

void add(vector<unique_ptr<Base>> list, const unique_ptr<Base>& ptr);

int main()
{
    vector<unique_ptr<Base>> list;
    unique_ptr<Base> derived(new Derived);
    add(list, derived);
}

void add(vector<unique_ptr<Base>> list, const unique_ptr<Base>& ptr)
{
    list.push_back(move(ptr));
}
Duc Nguyen
  • 11
  • 1

1 Answers1

3

There are quite a few issues with your code:

Here is the code corrected:

void add(std::vector<std::unique_ptr<Base>>& list, std::unique_ptr<Base> ptr)
{
    list.push_back(std::move(ptr));
}
int main()
{
    std::vector<std::unique_ptr<Base>> list;
    std::unique_ptr<Base> derived = std::make_unique<Derived>();

    add(list, std::move(derived));
}

// or

int main()
{
    std::vector<std::unique_ptr<Base>> list;

    add(list, std::make_unique<Derived>());
}
bolov
  • 72,283
  • 15
  • 145
  • 224
  • but i don't understand why we can't pass unique_ptr by ref? – Duc Nguyen May 03 '20 at 03:50
  • @DucNguyen you can pass by ref, just not by constant ref, nor lvalue ref. You can pass by rvalue ref (a.k.a. `&&`). The reason is because moving from an object modifies that object (to reflect the new state - moved from) so you cannot move from const. – bolov May 03 '20 at 03:58
  • oh, i see, that was harder than I thought – Duc Nguyen May 03 '20 at 05:56