为什么在C ++中用函数创建对象是不好的做法?

时间:2017-08-11 06:39:44

标签: c++ oop data-structures linked-list

我是C ++的新手。采访者说在一个函数中创建一个对象是不好的做法。是这样吗?

#include <iostream.h>

class linkedlist {
    int value;
    linkedlist *next;
    static linkedlist *p=NULL;

    void insert(int data) {
        linkedlist node;
        node.value=data;
        node.next=NULL;

        if(p==NULL)
            p=node;
        else {
            p->next=node;
            p=p->next;
        }
    }
}

int main() {
    linkedlist h;
    h.insert(10);
    h.insert(20);
    return 0;
}

1 个答案:

答案 0 :(得分:5)

问题是“终身”;您创建的节点仅存在于函数的堆栈帧中,当函数终止时,它的内存将被回收。然而,静态指针p仍将链接它,当有人稍后访问链表时,这将导致“未定义的行为”。

一般来说,使用本地对象并不坏,如果你期望它们在函数结束时存活,那就太糟糕了,因为它们没有。

您应该使用new将免费商店中的对象分配为长寿命对象。