std::vector 中止问题

发布于 2024-10-10 13:03:36 字数 961 浏览 4 评论 0原文

我对下面的示例遇到困难,最后一行产生“已调用中止”错误。我不明白为什么会这样。

在这种情况下,为了清楚起见,我使用 (*abc).def 而不是 abc->def 。

#include <iostream>
#include <string>
#include <vector>

class branch
{
    public:
        unsigned short n;
        std::vector<branch> branches;

        branch left()
        {
            return branches.at(0);
        }
};

void main()
{
    branch trunk = branch();
        trunk.n = 0;
        branch b1, b2;
        b1.n = 0;
        b2.n = 5;
        b1.branches.push_back(b2);
        trunk.branches.push_back(b1);

    branch* focus1 = &(trunk.branches.at(0));
    branch* focus3 = &(trunk.left());

    std::cout<<trunk.left().branches.at(0).n<<std::endl; // ok
    std::cout<<(*focus1).branches.at(0).n<<std::endl; // ok
    std::cout<<(*focus1).left().n<<std::endl; // ok
    std::cout<<(*focus3).branches.at(0).n<<std::endl; // problem
}

I'm having diffuculty with the example below, the last line is producing an "abort has been called" error. I don't see why this should be.

I'm using (*abc).def instead of abc->def for clarity in this case.

#include <iostream>
#include <string>
#include <vector>

class branch
{
    public:
        unsigned short n;
        std::vector<branch> branches;

        branch left()
        {
            return branches.at(0);
        }
};

void main()
{
    branch trunk = branch();
        trunk.n = 0;
        branch b1, b2;
        b1.n = 0;
        b2.n = 5;
        b1.branches.push_back(b2);
        trunk.branches.push_back(b1);

    branch* focus1 = &(trunk.branches.at(0));
    branch* focus3 = &(trunk.left());

    std::cout<<trunk.left().branches.at(0).n<<std::endl; // ok
    std::cout<<(*focus1).branches.at(0).n<<std::endl; // ok
    std::cout<<(*focus1).left().n<<std::endl; // ok
    std::cout<<(*focus3).branches.at(0).n<<std::endl; // problem
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

雄赳赳气昂昂 2024-10-17 13:03:36

此代码的问题在于 trunk.left() 返回分支的副本,而不是对该分支的引用。因此,您的 focus3 指针指向一个临时对象,该对象将在该行代码执行完毕后立即被清除。因此,当您尝试在最后一行取消引用 focus3 时,您将跟踪指向垃圾数据的指针,这会导致崩溃。

要解决此问题,请让 left 返回对分支的引用,或将 focus3 设置为 const 引用,这会将临时引用的生命周期延长到引用的生命周期。

The problem with this code is that trunk.left() returns a copy of the branch, not a reference to the branch. Consequently, your focus3 pointer is pointing at a temporary object that's immediately going to be cleaned up after that line of code finishes executing. Consequently, when you try dereferencing focus3 on the last line, you're following a pointer to garbage data, which causes the crash.

To fix this, either have left return a reference to the branch, or make focus3 a const reference, which extends the lifetime of the temporary to the lifetime of the reference.

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