当一个已经存在的指针被压入堆栈时,是否会创建它的副本?
void deleteAllNodes ()
{
stack <parentBranch *> mystack;
// `trunk` is the existing head node
mystack.push (trunk);
cout << mystack.top ()->content;
}
在这种情况下,主干的“副本”被推入堆栈中?那么,这是否意味着内存中同时存在两个树干?
void deleteAllNodes ()
{
stack <parentBranch *> mystack;
// `trunk` is the existing head node
mystack.push (trunk);
cout << mystack.top ()->content;
}
In this case a "copy" of trunk gets pushed in the stack? So, does this means that at a time there are two trunks present in the memory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有。
trunk
指向一个对象,但不是对象本身。就像一个标牌,上面写着“汽车 -->”旁边有一辆汽车。当您将trunk
推入mystack
时,您不会得到另一辆车。你只会看到另一个指向同一辆车的标志。如果你把车开走了(即
删除后备箱;
),那就太糟糕了。然后你会看到一大堆指向汽车的标志,但是当有人走过并试图进入那辆车时,他们会摔倒在地。所有指向汽车的标志都是骗子。Nope.
trunk
points to an object, but isn't the object itself. Like a sign that reads "Car -->" next to a car. When you pushtrunk
ontomystack
, you don't get another car. You just get another sign pointing to the same car.Woe be it if you drive the car off (i.e.
delete trunk;
). Then you'll have a whole bunch of signs that point to a car, but when someone comes along and tries to get in that car, they'll fall flat on their rear. All the signs pointing to the car will be liars.指针的副本被推送,但不是它指向的对象的副本。
A copy of the pointer gets pushed, but not a copy of the object it points to.
不,只有一个
trunk
,但有两个指针指向它。这就是标准库容器不取得指针成员的内存释放所有权的原因,因为它们无法确定谁实际上拥有所指向的对象,即驻留的指针容器内或用于推送操作的容器内。
如果您使用指针作为容器元素,则必须进行手动内存管理,由用户来确保指向对象保持有效。
这就是人们应该在标准库容器中使用智能指针而不是原始指针的原因,它可以节省您手动内存管理的时间。
如果被推入的元素不是指针而是一个对象,那么将有该对象的两个单独的副本,一个存储在容器中,另一个用于推入容器。
No there is only one
trunk
but two pointers pointing to it.This is the reason, Standard Library containers do not take ownership of deallocating memory of pointer members, because they cannot determine who actually owns the object being pointed to, the pointer which resides inside the container or the one which was used for push operation.
If you are using an pointer as container element, you are forced to do the manual memory management, it is up to the user to ensure the pointed to object remains valid.
This is the reason one should use smart pointers and not raw pointers with Standard Library containers, it saves you the manual memory management.
If the element being pushed in is not an pointer but an object then there will be two separate copies of the object, One which gets stored in the container and another which was used for push in to the container.