【发布时间】:2021-02-14 21:31:06
【问题描述】:
如何在这里使用智能指针?
#include <iostream>
using namespace std;
struct node
{
char data;
node *next;
};
class linked_list
{
private:
node *head,*tail,*tmp;
public:
linked_list()
{
head = nullptr;
tail = nullptr;
}
void add_node()
{
tmp = new node();
cin>> tmp->data;
tmp->next = nullptr;
if(head == nullptr)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
void print()
{
tmp=head;
while(tmp!=nullptr)
{
cout<<tmp->data;
tmp=tmp->next;
cout<<endl;
}
}
};
int main()
{
linked_list a;
a.add_node();
a.add_node();
a.add_node();
a.add_node();
a.print();
return 0;
}
如何更改add_note 函数的第一行代码以使用智能指针,而以后不必担心new/delete。需要进行哪些更改?我应该更改多行代码吗?如果有,那么在哪里?
【问题讨论】:
-
你不会只改变那个指针;你把它们都改了。
-
您能在此处输入代码并进行更改吗?我对 smart_ptr 有点陌生。
标签: c++ c++11 dynamic-memory-allocation smart-pointers