【问题标题】:Struct variable in class in heap and usage of smart pointer堆中类中的结构变量和智能指针的使用
【发布时间】: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


【解决方案1】:

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;
}

一些注意事项:

  1. 我已删除 tmp 成员变量,没有充分的理由将其作为成员变量。
  2. tail 是一个原始指针,因为节点是通过来自 head 成员的链拥有的
  3. 您可以使用 shared_ptr 而不是 unique_ptr,但对于链表来说,单一所有权链似乎更有意义

【讨论】:

  • 我会使用std::make_unique 来完全避免new
猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 2019-02-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多