我试图通过做一个简单的链表程序来学习 C++11 unique_ptr 的用法。我一生都无法弄清楚为什么在使用自定义删除时会出现编译错误。
#include <cstdio>
#include <limits>
#include <memory>
#include <cstdlib>
#include <iostream>
using namespace std;
struct node {
int value;
struct node* next;
};
typedef struct node Node;
std::unique_ptr<Node> createList()
{
std::unique_ptr<Node> head(new Node);
Node* temp=head.get();
temp->value=0;
for(int i=1;i<8;i++) {
if(temp->next==nullptr) {
temp->next=new Node();
temp=temp->next;
temp->value=i;
temp->next=nullptr;
}
//temp=temp->next;
}
return head;
}
int main()
{
auto del1 = [](Node* p) { while(p) {std::cout << "Deleting value is : " << p->value;struct node* n=p->next;delete p; p=n;} return; }; …Run Code Online (Sandbox Code Playgroud)