0
votes

I don't know what I'm doing wrong but I have problems with push function. Could you help me?

#include<iostream>
#include<memory>
using namespace std;

struct lista {
    int value;
    unique_ptr<lista>next;

    lista(int value):value(value), next(nullptr){}


};
void push(int x, unique_ptr<lista> &h) {
    unique_ptr<lista>alok_pam_x = make_unique<lista>(x);
    if (alok_pam_x!= nullptr)
    {
        (alok_pam_x->next) = h;
        h = alok_pam_x;

    }

}

And I have the error:

Severity Code Description Project File Line Suppression State Error C2280 'std::unique_ptr> &std::unique_ptr<_Ty,std::default_delete<_Ty>>::operator =(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
Severity Code Description Project File Line Suppression State Error (active) function "std::unique_ptr<_Ty, _Dx>::operator=(const std::unique_ptr<_Ty, _Dx>::_Myt &) [with _Ty=lista, _Dx=std::default_delete]" (declared at line 1436 of "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\memory") cannot be referenced -- it is a deleted function

1

1 Answers

0
votes

You're attempting to copy unique_ptr in two places, but a unique_ptr is a move only type, it cannot be copied. You need to std::move it instead.

Also, the check for nullptr after calling make_unique is pointless because if the allocation fails, it'll throw std::bad_alloc and the check will never be reached.

So your push function should look like this

void push(int x, unique_ptr<lista> &h) {
    auto alok_pam_x = make_unique<lista>(x);
    alok_pam_x->next = move(h);
    h = move(alok_pam_x);
}

Finally, you should probably consider making push a member function of lista.