简体   繁体   English

EXC_BAD_ACCESS 仅在 function 内构建 object 时

[英]EXC_BAD_ACCESS only when building object inside function

I'm working on a C++ project in XCode and I'm getting what appears to be some strange behavior (based on how I understand it).我正在 XCode 的 C++ 项目上工作,我得到了一些奇怪的行为(根据我的理解)。 Here's my code:这是我的代码:

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

class beep {
public:
    virtual void greet() {
        std::cout << "bleep\n";
    }
};

class boop : public beep {
public:
    void greet() {
        std::cout << "bloop\n";
    }
};

class beep_master {
public:
    std::vector<beep*> beeps;

    void beep_everything() {
        for (int i = 0; i < beeps.size(); i++) {
            beeps[i]->greet();
        }
    }
};

beep_master factory() {
    boop boop1;
    boop boop2;

    beep_master master;
    master.beeps.push_back(&boop1);
    master.beeps.push_back(&boop2);

    return master;
}

int main(int argc, const char * argv[]) {
    beep_master master = factory();

    beep_master* ref = &master;

    ref->beep_everything();

    return 0;
}

I'm running this via XCode, and I'm getting an EXC_BAD_ACCESS in the for -loop in beep_master .我正在通过 XCode 运行它,并且我在EXC_BAD_ACCESSfor循环中获得了beep_master Everywhere I've looked on the internet seems to indicate this is due to some memory management issues but I'm not really allocating anything dynamically.我在互联网上看到的所有地方似乎都表明这是由于一些 memory 管理问题,但我并没有真正动态地分配任何东西。

I've noticed that if I move the contents of factory into main that I no longer get the error which leads me to believe it has something to do with boop1 and boop2 going out of scope and making the pointers invalid after the code exits that function.我注意到,如果我将factory的内容移动到main中,我将不再收到错误,这使我相信它与boop1boop2走出 scope 并在代码退出 function 后使指针无效有关.

Noodling on this, I'm beginning to think that this issue is unavoidable without the use of dynamic memory via the new operator and shared_ptr .对此,我开始认为如果不通过new运算符和shared_ptr使用动态 memory ,这个问题是不可避免的。 Is this the right direction, or am I missing something in my setup here?这是正确的方向,还是我在这里的设置中遗漏了什么?

You are right.你说的对。 The factory function is storing pointers to local variables boop1 and boop2 which go away when the function returns, so you're left with pointers that point to invalid data. factory function 正在存储指向局部变量boop1boop2的指针,当 function 返回时,go 离开了,所以你指向的数据是无效的。

You're pretty much going to have to dynamically allocate your objects to store the pointers in your vector.您几乎必须动态分配对象以将指针存储在向量中。

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

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