如何解决堆中的类中的结构变量和智能指针的用法
如何在此处使用智能指针?
#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
。需要哪些更改?我是否需要更改多行代码?如果是这样,那又在哪里?
解决方法
std::unique_ptr
在这里可能是最合适的:
#include <iostream>
#include <memory>
struct node
{
char data;
std::unique_ptr<node> next;
};
class linked_list
{
private:
std::unique_ptr<node> head;
node* tail;
public:
linked_list()
: tail( nullptr )
{
}
void add_node()
{
std::unique_ptr<node> tmp(new node());
std::cin >> tmp->data;
if(head == nullptr)
{
head = std::move(tmp);
tail = head.get();
}
else
{
tail->next = std::move(tmp);
tail = tail->next.get();
}
}
void print()
{
auto tmp=head.get();
while(tmp!=nullptr)
{
std::cout << tmp->data;
tmp = tmp->next.get();
std::cout << "\n";
}
}
};
int main()
{
linked_list a;
a.add_node();
a.add_node();
a.add_node();
a.add_node();
a.print();
return 0;
}
一些注意事项:
- 我已经删除了
tmp
成员变量,没有充分的理由将其作为成员变量。 -
tail
是原始指针,因为节点是通过head
成员的链来拥有的。 - 您可以使用
shared_ptr
而不是unique_ptr
,但是对于链接列表来说,单一所有权链似乎更有意义
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。