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
You're attempting to copy
unique_ptr
in two places, but aunique_ptr
is a move only type, it cannot be copied. You need tostd::move
it instead.Also, the check for
nullptr
after callingmake_unique
is pointless because if the allocation fails, it'll throwstd::bad_alloc
and the check will never be reached.So your
push
function should look like thisFinally, you should probably consider making
push
a member function oflista
.