简体   繁体   English

使用链表会导致内存泄漏吗?

[英]Would this cause a memory leak using linked lists?

I am programming a template for singly linked lists in C++ and I am getting confused about what would be the right way of returning the information of the first node when deleting it. 我正在为C ++中的单链列表编写模板,而对于删除它时返回第一个节点信息的正确方法感到困惑。

I am getting some help from a book where there are written two methods, one that returns the value of the head node, and other that deletes it. 我从一本书中获得了一些帮助,该书中编写了两种方法,一种返回头节点的值,另一种将其删除。 Let's call that methods front() and pop(), where front() returns the value with a "const T&" type. 我们将其称为front()和pop()方法,其中front()返回具有“ const T&”类型的值。 One of my questions is, if I do something like this: 我的问题之一是,如果我做这样的事情:

T object = list.front();
list.pop();

Wouldn't that result in an object reference pointing to nothing? 那会不会导致对象引用什么都没有指向? Is there any problem if I continue using that object after calling pop()? 如果在调用pop()之后继续使用该对象,是否会有任何问题?

A second question is, what's the correct way of using the front() method and what's the difference between: 第二个问题是,使用front()方法的正确方法是什么以及它们之间的区别是什么:

T object = list.front();
// or
T& object = list.front();
// or
const T& object = list.front();

If you do 如果你这样做

T object = list.front();

and front() returns T& , then object becomes a copy of the initial element of the list, not a reference to it. 并且front()返回T& ,然后object成为列表初始元素的副本 ,而不是对其的引用。

If, on the other hand, you write 另一方面,如果您写

const T& ref = list.front();

then the call to list.pop() would make ref a dangling reference, which is different from memory leak. 那么对list.pop()的调用将使ref成为悬挂的引用,这与内存泄漏不同。

This should explain the difference between your first and third example; 这应该解释您的第一个示例和第三个示例之间的区别; your second example, ie 你的第二个例子,即

T& object = list.front();

would not compile, because non- const reference cannot be constructed from a const reference. 不会编译,因为非const引用不能从一个被构造const参考。

For T object = list.front(); 对于T object = list.front(); , object is a copy of list.front() and then has nothing to do with the original element. objectlist.front()的副本, list.front()与原始元素无关。 So list.pop() doesn't have any influence on it at all. 因此list.pop()完全没有影响。

For T& object = list.front(); 对于T& object = list.front(); , you can't do that. ,您不能那样做。 const T& can't be implicitly converted to T& . const T&不能隐式转换为T&

For const T& object = list.front(); 对于const T& object = list.front(); , object is a reference to the element in list . ,object是对list元素的引用。 So after list.pop() it will be dangled. 因此,在list.pop() ,它将被悬挂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM