为什么在推入链表之前应该复制或克隆数据?

时间:2014-03-27 03:34:37

标签: c++ linked-list

我的问题是关于将地址传递给链表的推送功能,所以为什么在这段代码中推送数据地址是不够的,为什么数据应该首先由new int (i)复制,当地址只使用时,内存会发生什么:

 #include <iostream>
using namespace std ;

struct holder
{
    struct node
    {
        node* next ;
        void* value ;
    }*top;
    void initialize() ;
    void *pop();
    void push(void*val) ;
};

void holder::initialize()
{
    top = 0 ;
}
void holder::push(void*val)
{
    node* newnode = new node;
    newnode->value = val ;
    newnode->next = top ;
    top = newnode ;
}

void* holder::pop()
{
    void* result ;
    node* oldtop ;
    result = top->value ;
    oldtop = top ;
    top = top->next ;
    delete oldtop ;
    return result ;
}

int main()
{
    holder test ;
    test.initialize() ;
    for(int i = 0 ; i <10 ; i++)
    {
        // test.push (&i) ;   not working
        test.push(new int (i)) ;
    }
    for(int i = 0 ; i <10 ; i++)
    {
        cout << *(int*)test.pop() << endl ;
    }

}

2 个答案:

答案 0 :(得分:1)

test.push (&i)

推送永不改变的i地址,10x。

test.push(new int (i)) ;

创建一个新的唯一变量10x并将唯一地址推送到列表中。

您可以考虑使用templates rather than void pointers.

答案 1 :(得分:1)

在你的“不工作”代码中,你每次都按下相同的指针,并且我不像我那样改变。因此,您将拥有该局部变量的相同指针的10个副本。该列表仅包含指向值的指针,因此您需要分配内存以实际放置值。

此外,在从堆栈中检索指针后,您需要删除已分配的内存。像这样:

int *value = (int*)test.pop();
cout << *value << endl ;
delete value;

在这种情况下,对新事物的需求可能更为明显。