Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在链表中析构函数是必需的吗?_C++_Linked List_Destructor - Fatal编程技术网

C++ 在链表中析构函数是必需的吗?

C++ 在链表中析构函数是必需的吗?,c++,linked-list,destructor,C++,Linked List,Destructor,我制作了一个单链表程序 我想知道是否需要析构函数或默认析构函数可以正常工作 class sll { node*head; node*tail; public: sll() { head=tail=0; } sll(const sll & obj1); void addtohead (int x); void addtotail (int x); int deletefromhead(); in

我制作了一个单链表程序

我想知道是否需要析构函数或默认析构函数可以正常工作

class sll
{
    node*head;
    node*tail;
public:
    sll()
    {
        head=tail=0;
    }
    sll(const sll & obj1);
    void addtohead (int x);
    void addtotail (int x);
    int deletefromhead();
    int deletefromtail();
}

默认析构函数将只释放head和tail的内存,因为sll()构造函数仅在对象初始化时将head和tail初始化为0

它不适用于动态分配的节点

~sll()
{
    node *p = head;
    while (head !=NULL)
    {
        head= head -> next;
        delete p;
        p=head;
    }
}

析构函数不是强制性的,除非您试图开发RAII或好的代码

如果您没有包含析构函数,那么您会给使用您的类的人带来负担:他们需要知道您没有析构函数,他们必须在让节点超出范围或销毁节点之前删除节点

考虑“ifstream”类

我们不需要执行“file.close()”或执行任何其他清理。这一切都包含在我们与istream的合同中。当物体离开时,它做了正确的事情

与“std::string”类似——您不必这样做

std::string greeting = "Hello, ";
greeting += username;
std::cout << greeting << std::endl;
greeting.freeMemory();
std::string问候语=“你好,”;
问候语+=用户名;

std::cout请不要为指针编写
=0
。写
=NULL
或者如果您有C++11,则写
=NULL ptr
;每当您在类中使用指针时,强烈建议使用析构函数。@kfsone对于C++03,我通常看到完全相反的建议,首选
=0
。是的<代码>标准::cout
void func(int);void func(char*);int test(){func(0);}
vs
void func(int);void func(char*);int test(){func(NULL);}
(nullptr是为了解决这个问题而设计的,但这里我讨论的是可读性和可维护性)。
std::string greeting = "Hello, ";
greeting += username;
std::cout << greeting << std::endl;
greeting.freeMemory();