当一个已经存在的指针被压入堆栈时,是否会创建它的副本?

发布于 2025-01-01 21:25:02 字数 259 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

念﹏祤嫣 2025-01-08 21:25:02

没有。 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 push trunk onto mystack, 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.

街角卖回忆 2025-01-08 21:25:02

指针的副本被推送,但不是它指向的对象的副本。

A copy of the pointer gets pushed, but not a copy of the object it points to.

够运 2025-01-08 21:25:02

不,只有一个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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文