Hello I am trying to use pointers and learning the basics on unique pointers in C++. Below is my code I have commented the line of code in main function. to debug the problem However, I am unable to do so. What am I missing ? Is my move() in the insertNode() incorrect ? The error I get is below the code :
#include<memory>
#include<iostream>
struct node{
int data;
std::unique_ptr<node> next;
};
void print(std::unique_ptr<node>head){
while (head)
std::cout << head->data<<std::endl;
}
std::unique_ptr<node> insertNode(std::unique_ptr<node>head, int value){
node newNode;
newNode.data = value;
//head is empty
if (!head){
return std::make_unique<node>(newNode);
}
else{
//head points to an existing list
newNode.next = move(head->next);
return std::make_unique<node>(newNode);
}
}
auto main() -> int
{
//std::unique_ptr<node>head;
//for (int i = 1; i < 10; i++){
// //head = insertNode(head, i);
//}
}
ERROR std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
const node&. As print function doesn't keep any reference to the parameter after it returns, it doesn't need to know about how it is managed. - Neil Kirkprintis broken in other ways too -- right now it is an infinite loop. AndinsertNodeneeds to be pass-by-reference also - Ben Voigtunique_ptrlike this. For example, by passing aunique_ptrto your print function, you're implying that it is taking ownership of the pointer; when really that isn't the case. The enclosing scope of aunique_ptris said to be the sole owner of it (which is why it's called unique); you can move this ownership but not share/copy it. Ashared_ptr, on the other hand, represents ownership that is shared; a raw/weak pointer or reference (probably what your print function should accept...constqualified) generally indicates a lack of ownership. - Julian