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

use*_*993 1 c++ oop linked-list data-structures

我是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;
}
Run Code Online (Sandbox Code Playgroud)

650*_*502 5

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

一般来说,使用本地对象并不坏,只要你期望它们在函数结束时存活就会很糟糕,因为它们没有.

你应该通过使用在免费商店中分配长生活对象new.