gpt4 book ai didi

C++ exc_bad_access 从 unordered_map 中指向的对象访问字符串字段

转载 作者:行者123 更新时间:2023-11-28 02:33:58 26 4
gpt4 key购买 nike

我正在尝试通过以下方式维护快速访问 vector :

我的类.h:

class MyClass{
private:
std::vector<Stuff> myStuffList;
std::tr1::unordered_map<std::string,Stuff*> myStuffListIndex;
...
public:
void addToStuffList(std::string key,Stuff stuff);

};

我的类.cpp:

...
void MyClass::addToStuffList(std::string name, Stuff stuff){
myStuffList.push_back(stuff);//our man is guaranteed to be at tail
myStuffListIndex[name] = &myStuffList[myStuffList.size()-1];//store
//pointer to object that we just copy-constructed at tail of list
}

东西.h:

class Stuff{
private:
std::string name;
public:
Stuff();
Stuff(const Stuff&);
Stuff& operator=(const Stuff&);
...

};

东西.cpp:

Stuff::Stuff() : name(""){}
Stuff::Stuff(const Stuff& other){
if(this != &other){
this->name = other.name;
}
}
Stuff& Stuff::operator=(const Stuff& other){
if(this != &other){
this->name = other.name;
}
}
std::string Stuff::getName(){
return name;//exc_bad_access triggered here
}

稍后,当我尝试通过 map 访问 vector 中的项目时,出现明显间歇性的 exc_bad_access 错误,如下所示:

void methodA(){
Stuff localStuff;
myClassInstance.addToStuffList("mostrecentstuff",localStuff);
}
...
void methodB(){
//different method now, localStuff would be out of scope but
//shouldn't matter since we passed by value in addToStuffList, right?
Stuff* pStuff = myStuffListIndex["mostrecentstuff"];
std::cout << "Hello, my name is " << pStuff->getName() << std::endl;
}

int main(int argc, const char* argv[]){
methodA();
methodB();
}

为什么访问 pStuff->getName() 会抛出 exc_bad_access?

最佳答案

正如 PaulMcKenzie 所说, vector 可以调整大小,如果可以,它可以重新定位到不同的地址。然后所有指向先前 vector 项的指针都被破坏。

你不应该保留指向 std 容器中项目的指针,但对于 vector ,你可以保留它们的索引。

你会:

std::vector<Stuff> myStuffList;
std::tr1::unordered_map<std::string,int> myStuffListIndex;

myStuffList.push_back(ability);//our man is guaranteed to be at tail 
myStuffListIndex[name] = myStuffList.size() - 1;//store

如果您的应用程序是多线程的,则必须使用互斥体来保护上述代码

关于C++ exc_bad_access 从 unordered_map 中指向的对象访问字符串字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28166905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com