【问题标题】:Is Destructor is mandatory in linked lists?析构函数在链表中是强制性的吗?
【发布时间】:2013-11-16 00:43:39
【问题描述】:

我做了一个单链表程序。

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

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

【问题讨论】:

  • 请不要写= 0作为指针。写 = NULL 或者如果你有 C++11 写 = nullptr;
  • 在类中使用指针时强烈建议使用析构函数。
  • @kfsone 我通常看到与 C++03 完全相反的建议,首选 =0
  • 是的。 std::cout << "sizeof(0) " << sizeof(0) << ", sizeof(NULL) " << sizeof(NULL) << ", sizeof(void*) " << sizeof(void*) << std::endl;。此外,当您遇到 0/NULL 解析为整数并调用与预期不同的指纹的情况时,需要更长的时间才能意识到作者打算传递空指针而不是 bool/int/whatever 它如果他们传递 '0' 而不是 'NULL',则被强制转换为。
  • void func(int); void func(char*); int test() { func(0); } vs void func(int); void func(char*); int test() { func(NULL); }(nullptr 就是为了解决这个问题而设计的,但这里我说的是可读性和可维护性)。

标签: c++ linked-list destructor


【解决方案1】:

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

它不适用于动态分配的节点。在您的类中实现以下代码。

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

【讨论】:

    【解决方案2】:

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

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

    考虑“ifstream”类。

    void function(const char* filename) {
        if (!haveReadFile) {
            ifstream file(filename); // create 'file' and open filename.
            if (file.good()) {      // file opened.
                readFile(file);
                haveReadFile = true;
            }
        }
        // .. other stuff.
    }
    

    我们不需要在这里执行“file.close()”或进行任何其他清理。这一切都封装在我们与 istream 签订的合同中。当对象离开时,它做了正确的事情。

    同样使用 "std::string" -- 你不必这样做

    std::string greeting = "Hello, ";
    greeting += username;
    std::cout << greeting << std::endl;
    greeting.freeMemory();
    

    因为字符串有析构函数,所以合约不需要你主动管理它的资源。

    所以:不管析构函数是否是强制性的——如果没有析构函数,当你的类超出范围时发生的行为是否有意义?会不会有内存泄露?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2013-03-18
      • 2013-04-26
      • 2012-10-15
      • 2018-03-27
      • 2016-09-24
      相关资源
      最近更新 更多